<?php

/**
 * 订单管理
 * @author cjli
 *
 */
class OrderAction extends AdminAction
{
    public function _initialize()
    {
        parent::_initialize();
    }


    //订单列表
    public function order_list_items()
    {
        session_start();
        //订单自动确认
        OrderModel::orderAutoConfirmedOneMonth();

        $post = $_REQUEST;

//		//发货列表
//		if(isset($_GET['order_status']) && intval($_GET['order_status'])==1 && isset($_GET['payment_status']) && intval($_GET['payment_status'])==1 && isset($_GET['shipping_status']) && intval($_GET['shipping_status'])==0 ){
//			$_POST['search'] = 1;
//			$_POST['order_status'] = 1;
//			$_POST['payment_status'] = 1;
//			$_POST['shipping_status'] = 0;
//		}

        //根据buttonselect作判断
        $buttonselect = $post['buttonselect'];
        if ($buttonselect == 'wait') {
            $post['order_status'] = 1;
            $post['payment_status'] = 1;
            $post['start_time'] = date('Y-m-d H:i:s', time() - 3600 * 24);
        } else if ($buttonselect == 'ok') {
            $post['order_status'] = 1;
            $post['payment_status'] = 1;
            $post['end_time'] = date('Y-m-d H:i:s', time() - 3600 * 24);
        } else if ($buttonselect == 'pause') {
            $post['order_status'] = -3;
        } else {
            $buttonselect = "all";
        }
        $this->assign('buttonselect', $buttonselect);
        // var_dump($post);die;
        $where = array();
        //合作伙伴专用
        if ($_REQUEST['address_id']) {
            $where['address_id'] = $_REQUEST['address_id'];
        }

        //搜索订单状态
        $order_status = 9999;
        if (isset($post['order_status']) && $post['order_status'] != 9999) {
            $where['orders.order_status'] = $post['order_status'];
            $order_status = $post['order_status'];
        }
        $this->assign('order_status', $order_status);
        //搜索支付状态
        $payment_status = 9999;
        if (isset($post['payment_status']) && $post['payment_status'] != 9999) {
            $where['orders.payment_status'] = $post['payment_status'];
            $payment_status = $post['payment_status'];
        }
        $this->assign('payment_status', $payment_status);
        //搜索配送状态
        $shipping_status = 9999;
        if (isset($post['shipping_status']) && $post['shipping_status'] != 9999) {
            $where['orders.shipping_status'] = $post['shipping_status'];
            $shipping_status = $post['shipping_status'];
        }
        $this->assign('shipping_status', $shipping_status);
        //搜索关键词
        if (isset($post['keyword']) && $post['keyword']) {
            $post['keyword'] = trim($post['keyword']);
            if ($post['searchtype'] == 0) {
                $where['orders.order_sn'] = array('like', '%' . $post['keyword'] . '%');
            } else if ($post['searchtype'] == 1) {
                //$where['orders.delivery_last_name'] = array('like', '%'.$post['keyword'].'%');
                $where[] = "orders.delivery_last_name LIKE '%{$post['keyword']}%' OR orders.delivery_first_name LIKE  '%{$post['keyword']}%'";
            } else if ($post['searchtype'] == 2) {
                $where['orders.payment_time'] = array('like', '%' . strtotime($post['keyword']) . '%');
            } else if ($post['searchtype'] == 3) {
                $where['orders.id'] = $post['keyword'];
            } else if ($post['searchtype'] == 4) {
                $user_id = M('users')->where(array('email' => $post['keyword']))->getField('id');
                $where['orders.user_id'] = $user_id > 0 ? $user_id : '-999';
            }
            $this->assign('keyword', $post['keyword']);
        }
        $this->assign('searchtype', $post['searchtype']);
        //付款时间查询
        $orders = D('orders');
        //if(isset($post['time_search'])){ 
        if ($post['start_time'] && $post['end_time']) {
            $start_time = strtotime($post['start_time']);
            $end_time = strtotime($post['end_time']);
            $where['payment_time'] = array(array('egt', $start_time), array('lt', $end_time), 'and');
        } else {
            if ($post['start_time']) {
                $start_time = strtotime($post['start_time']);
                $where['payment_time'] = array('egt', $start_time);
            }
            if ($post['end_time']) {
                $end_time = strtotime($post['end_time']);
                $where['payment_time'] = array('lt', $end_time);
            }
        }
        $this->assign('start_time', $post['start_time']);
        $this->assign('end_time', $post['end_time']);
        //}

        if ($post['yushou_order_type'] > 0) {
            if ($post['yushou_order_type'] == 1) {
                $where['orders.product_dingjin'] = array('gt', 0);
            } else {
                $where['orders.product_dingjin'] = 0;
            }
        }


        if ($_POST['dosubmit']) {
            $where = 1;
            if ($_POST['order_sn'])
                $where .= ' AND order_sn like "%' . $_POST['order_sn'] . '%"';
            if ($_POST['delivery_email'])
                $where .= ' and delivery_email like "%' . $_POST['delivery_email'] . '%"';
            if ($_POST['delivery_name'])
                $where .= ' and delivery_name like "%' . $_POST['delivery_name'] . '%"';
            if ($_POST['delivery_postcode'])
                $where .= ' and delivery_postcode like "%' . $_POST['delivery_postcode'] . '%"';
            if ($_POST['delivery_phone'])
                $where .= ' and delivery_phone like "%' . $_POST['delivery_phone'] . '%"';
            if ($_POST['delivery_mobile'])
                $where .= ' and delivery_mobile like "%' . $_POST['delivery_mobile'] . '%"';
            if ($_POST['delivery_cid'] > 0)
                $where .= ' and delivery_cid = "' . $_POST['delivery_cid'] . '"';
            if ($_POST['delivery_province'])
                $where .= ' and delivery_province like "%' . $_POST['delivery_province'] . '%"';
            if ($_POST['delivery_city'])
                $where .= ' and delivery_city like "%' . $_POST['delivery_city'] . '%"';
            if ($_POST['shipping_method'] > 0)
                $where .= ' and shipping_method = "' . $_POST['shipping_method'] . '"';
            if ($_POST['payment_method'] > 0)
                $where .= ' and payment_method = "' . $_POST['payment_method'] . '"';
            if ($_POST['start_time1'] && $_POST['start_time2']) {
                $where .= ' and start_time >"' . $_POST['start_time1'] . '" and start_time <= "' . $_POST['start_time2'] . '"';
            }
            if ($_POST['order_status'] > 0)
                $where .= ' and order_status =' . $_POST['order_status'] . '';
            if ($_POST['payment_status'] > 0)
                $where .= ' and payment_status =' . $_POST['payment_status'] . '';
            if ($_POST['shipping_status'] > 0)
                $where .= ' and shipping_status =' . $_POST['shipping_status'] . '';
            if ($_POST['delivery_address']) {
                $where .= ' and (delivery_address like "%' . $_POST['delivery_address'] . '%" or delivery_address2 like "%' . $_POST['delivery_address'] . '%" or delivery_address3 like "%' . $_POST['delivery_address'] . '%" or delivery2_address like "%' . $_POST['delivery_address'] . '%" or delivery2_address2 like "%' . $_POST['delivery_address'] . '%" or delivery2_address3 like "%' . $_POST['delivery_address'] . '%")';
            }
        }
        $order_db = D('orders');

        $pageRows = 20;
        if (isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])) {
            $pageRows = intval($_REQUEST['pageRows']);
        }
        if (!isset($post['order_status']) || $post['order_status'] != OrderModel::ORDER_DEL) {
            $where['_string'] = ' order_status !=' . OrderModel::ORDER_DEL;
        }


        $field = 'id,order_sn,order_amount,pay_amount,order_status,payment_status,
	              shipping_status,delivery_phone,delivery_mobile,delivery_address,
	              delivery_country,delivery_province,delivery_first_name,delivery_last_name,
	              confirm_time,payment_time,end_time,start_time,is_cheat,language_id,update_time,product_amount';
        $order = 'orders.id DESC';
        if ($buttonselect == 'ok') {
            $field .= ',IF(update_time>0, update_time ,payment_time) as u_time';
            $order = 'u_time DESC';
        }
        $order_db->field($field);
        $order_db->order($order);
        $order_db->where($where);
        $orderList = $order_db->select();

        $order_id_str = '';
        foreach ($orderList as $key => $val) {
            $order_id_str .= $val['id'] . ',';
        }

        $orders_items_where['_string'] = ' order_id in(' . trim($order_id_str, ',') . ')';
        $orders_items_db = D('orders_items');
        $orders_items_db->where($orders_items_where);
        $count = $orders_items_db->count();//总记录数
        import("ORG.Util.Page");// 导入分页类
        $Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
        $pageShow = $Page->show();// 分页显示输出
        $this->assign('pageShow', $pageShow);
        $nowPage = $Page->getNowPageUrl();//当前页url
        //如果是post过来的则跳转到带参数的url
        if ($_POST) {
            redirect($nowPage);
            exit;
        }
        //保存当前url
        //cookie('order_list_nowPage',$nowPage);		

        $field = '*';
        $order = 'id DESC';
        $orders_items_db->field($field);
        $orders_items_db->order($order);
        $orders_items_db->limit($Page->firstRow . ',' . $Page->listRows);
        $orders_items_db->where($orders_items_where);
        $orders_items_list = $orders_items_db->select();
        //$newOrderListRes
        $orders_list_pro = array();
        foreach ($orderList as $key => $val) {
            $orders_list_pro[$val['id']] = $val;
        }
        $newOrderList = array();
        foreach ($orders_items_list as $key => $val) {
            $newOrderListRes = $orders_list_pro[$val['order_id']];

            //占比
            $newOrderListRes['order_amount'] = $val['total_amount'];

            $b = $val['total_amount'] / $newOrderListRes['product_amount'];
            $pay_amount = $newOrderListRes['pay_amount'] * $b;
            $newOrderListRes['pay_amount'] = sprintf("%0.2f", $pay_amount);

            $newOrderListRes['items'] = $val;
            $newOrderList[$key] = $newOrderListRes;
        }

        $orderList = $newOrderList;

        $language_info = M('language')->field('id,name,name_cn')->select();
        $language = array();
        foreach ($language_info as $k => $v) {//后台显示语言
            $language[$v['id']] = array(
                'name' => $v['name'],
                'name_cn' => $v['name_cn']
            );
        }

        foreach ($orderList as $key => $val) {
            $orderList[$key]['is_size'] = OrderModel::isset_size($val['id']);
        }
        //查询被暂停的订单的数量
        $order_pause = $order_db->where(array('order_status' => OrderModel::ORDER_PAUSE))->count();
        $this->assign('order_pause', $order_pause);

        $yushou_order_type = $post['yushou_order_type'];
        $this->assign('language', $language);
        $this->assign('yushou_order_type', $yushou_order_type);
        $this->assign('orderList', $orderList);
        $this->assign('pageRows', $pageRows);
        $this->display('order_list_items');
    }

    //订单列表
    public function order_list()
    {
        session_start();
        //订单自动确认
        OrderModel::orderAutoConfirmedOneMonth();

        $post = $_REQUEST;

//		//发货列表
//		if(isset($_GET['order_status']) && intval($_GET['order_status'])==1 && isset($_GET['payment_status']) && intval($_GET['payment_status'])==1 && isset($_GET['shipping_status']) && intval($_GET['shipping_status'])==0 ){
//			$_POST['search'] = 1;
//			$_POST['order_status'] = 1;
//			$_POST['payment_status'] = 1;
//			$_POST['shipping_status'] = 0;
//		}

        //属性类型列表  导出订单定制选项用
        $modelList = AttributeModel::getModelList();
        $this->assign('modelList', $modelList);

        //根据buttonselect作判断
        $buttonselect = $post['buttonselect'];
        if ($buttonselect == 'wait') {
            $post['order_status'] = 1;
            $post['payment_status'] = 1;
            $post['start_time'] = date('Y-m-d H:i:s', time() - 3600 * 24);
        } else if ($buttonselect == 'ok') {
            $post['order_status'] = 1;
            $post['payment_status'] = 1;
            $post['end_time'] = date('Y-m-d H:i:s', time() - 3600 * 24);
        } else if ($buttonselect == 'pause') {
            $post['order_status'] = -3;
        } else {
            $buttonselect = "all";
        }
        $this->assign('buttonselect', $buttonselect);
        // var_dump($post);die;
        $where = array();
        //合作伙伴专用
        if ($_REQUEST['address_id']) {
            $where['address_id'] = $_REQUEST['address_id'];
        }
		if(isset($_GET['user_id']) && !empty($_GET['user_id'])){
			$where['user_id']  = I("get.user_id");
		}
        $where['class_id'] =0;
        //搜索订单状态
        $order_status = 9999;
        if (isset($post['order_status']) && $post['order_status'] != 9999) {
            $where['orders.order_status'] = $post['order_status'];
            $order_status = $post['order_status'];
        }
        $this->assign('order_status', $order_status);
        //搜索支付状态
        $payment_status = 9999;
        if (isset($post['payment_status']) && $post['payment_status'] != 9999) {
            $where['orders.payment_status'] = $post['payment_status'];
            $payment_status = $post['payment_status'];
        }
        $this->assign('payment_status', $payment_status);
        //搜索配送状态
        $shipping_status = 9999;
        if (isset($post['shipping_status']) && $post['shipping_status'] != 9999) {
            $where['orders.shipping_status'] = $post['shipping_status'];
            $shipping_status = $post['shipping_status'];
        }
        $this->assign('shipping_status', $shipping_status);
        //搜索关键词
        if (isset($post['keyword']) && $post['keyword']) {
            $post['keyword'] = trim($post['keyword']);
            if ($post['searchtype'] == 0) {
                $where['orders.order_sn'] = array('like', '%' . $post['keyword'] . '%');
            } else if ($post['searchtype'] == 1) {
                //$where['orders.delivery_last_name'] = array('like', '%'.$post['keyword'].'%');
                $where[] = "orders.delivery_last_name LIKE '%{$post['keyword']}%' OR orders.delivery_first_name LIKE  '%{$post['keyword']}%'";
            } else if ($post['searchtype'] == 2) {
                $where['orders.payment_time'] = array('like', '%' . strtotime($post['keyword']) . '%');
            } else if ($post['searchtype'] == 3) {
                $where['orders.id'] = $post['keyword'];
            } else if ($post['searchtype'] == 4) {
                $user_id = M('users')->where(array('email' => $post['keyword']))->getField('id');
                $where['orders.user_id'] = $user_id > 0 ? $user_id : '-999';
            } else if ($post['searchtype'] == 5) {
                $user_id = M('users')->where(array('phone' => $post['keyword']))->getField('id');
                $user_id = $user_id > 0 ? $user_id : '-999';
                $where[] = "orders.delivery_phone LIKE '%{$post['keyword']}%' OR orders.user_id = '{$user_id}'";
            }
            $this->assign('keyword', $post['keyword']);
        }
        $this->assign('searchtype', $post['searchtype']);
        //付款时间查询
        $orders = D('orders');
        //if(isset($post['time_search'])){ 
        if ($post['start_time'] && $post['end_time']) {
            $start_time = strtotime($post['start_time']);
            $end_time = strtotime($post['end_time']);
            $where['payment_time'] = array(array('egt', $start_time), array('lt', $end_time), 'and');
        } else {
            if ($post['start_time']) {
                $start_time = strtotime($post['start_time']);
                $where['payment_time'] = array('egt', $start_time);
            }
            if ($post['end_time']) {
                $end_time = strtotime($post['end_time']);
                $where['payment_time'] = array('lt', $end_time);
            }
        }
        $this->assign('start_time', $post['start_time']);
        $this->assign('end_time', $post['end_time']);
        //}

        //根据更新时间搜索
        if ($post['up_start_time'] && $post['up_end_time']) {
            $up_start_time = strtotime($post['up_start_time']);
            $up_end_time = strtotime($post['up_end_time']);
            $where['update_time'] = array(array('egt', $up_start_time), array('lt', $up_end_time), 'and');
        } else {
            if ($post['up_start_time']) {
                $up_start_time = strtotime($post['up_start_time']);
                $where['update_time'] = array('egt', $up_start_time);
            }
            if ($post['up_end_time']) {
                $up_end_time = strtotime($post['up_end_time']);
                $where['update_time'] = array('lt', $up_end_time);
            }
        }
        $this->assign('up_start_time', $post['up_start_time']);
        $this->assign('up_end_time', $post['up_end_time']);
        //根据更新时间搜索
        //根据下单时间搜索
        if ($post['c_start_time'] && $post['c_end_time']) {
            $c_start_time = strtotime($post['up_start_time']);
            $c_end_time = strtotime($post['c_end_time']);
            $where['start_time'] = array(array('egt', $c_start_time), array('lt', $c_end_time), 'and');
        } else {
            if ($post['c_start_time']) {
                $c_start_time = strtotime($post['c_start_time']);
                $where['start_time'] = array('egt', $c_start_time);
            }
            if ($post['c_end_time']) {
                $c_end_time = strtotime($post['c_end_time']);
                $where['start_time'] = array('lt', $c_end_time);
            }
        }


        if ($post['yushou_order_type'] > 0) {
            if ($post['yushou_order_type'] == 1) {
                $where['orders.product_dingjin'] = array('gt', 0);
            } else {
                $where['orders.product_dingjin'] = 0;
            }
        }

        if(!isset($post['is_gift_orders']) || (isset($post['is_gift_orders']) && $post['is_gift_orders']==0)){
            $where['orders.is_gift_orders'] = 0; //非礼品订单
        }else{
            $where['orders.is_gift_orders'] = 1; //礼品订单
        }


        if ($_POST['dosubmit']) {
            $where = 1;
            if ($_POST['order_sn'])
                $where .= ' AND order_sn like "%' . $_POST['order_sn'] . '%"';
            if ($_POST['delivery_email'])
                $where .= ' and delivery_email like "%' . $_POST['delivery_email'] . '%"';
            if ($_POST['delivery_name'])
                $where .= ' and delivery_name like "%' . $_POST['delivery_name'] . '%"';
            if ($_POST['delivery_postcode'])
                $where .= ' and delivery_postcode like "%' . $_POST['delivery_postcode'] . '%"';
            if ($_POST['delivery_phone'])
                $where .= ' and delivery_phone like "%' . $_POST['delivery_phone'] . '%"';
            if ($_POST['delivery_mobile'])
                $where .= ' and delivery_mobile like "%' . $_POST['delivery_mobile'] . '%"';
            if ($_POST['delivery_cid'] > 0)
                $where .= ' and delivery_cid = "' . $_POST['delivery_cid'] . '"';
            if ($_POST['delivery_province'])
                $where .= ' and delivery_province like "%' . $_POST['delivery_province'] . '%"';
            if ($_POST['delivery_city'])
                $where .= ' and delivery_city like "%' . $_POST['delivery_city'] . '%"';
            if ($_POST['shipping_method'] > 0)
                $where .= ' and shipping_method = "' . $_POST['shipping_method'] . '"';
            if ($_POST['payment_method'] > 0)
                $where .= ' and payment_method = "' . $_POST['payment_method'] . '"';
            if ($_POST['start_time1'] && $_POST['start_time2']) {
                $where .= ' and start_time >"' . $_POST['start_time1'] . '" and start_time <= "' . $_POST['start_time2'] . '"';
            }
            if ($_POST['order_status'] > 0)
                $where .= ' and order_status =' . $_POST['order_status'] . '';
            if ($_POST['payment_status'] > 0)
                $where .= ' and payment_status =' . $_POST['payment_status'] . '';
            if ($_POST['shipping_status'] > 0)
                $where .= ' and shipping_status =' . $_POST['shipping_status'] . '';
            if ($_POST['delivery_address']) {
                $where .= ' and (delivery_address like "%' . $_POST['delivery_address'] . '%" or delivery_address2 like "%' . $_POST['delivery_address'] . '%" or delivery_address3 like "%' . $_POST['delivery_address'] . '%" or delivery2_address like "%' . $_POST['delivery_address'] . '%" or delivery2_address2 like "%' . $_POST['delivery_address'] . '%" or delivery2_address3 like "%' . $_POST['delivery_address'] . '%")';
            }
            if(!isset($_POST['is_gift_orders']) || (isset($_POST['is_gift_orders']) && $_POST['is_gift_orders']==0)){
                $where .= ' and is_gift_orders = 0'; //非礼品订单
            }else{
                $where .= ' and is_gift_orders = 1';; //礼品订单
            }
        }
        $order_db = D('orders');

        $pageRows = 20;
        if (isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])) {
            $pageRows = intval($_REQUEST['pageRows']);
        }
        if (!isset($post['order_status']) || $post['order_status'] != OrderModel::ORDER_DEL) {
            $where['_string'] = ' order_status !=' . OrderModel::ORDER_DEL;
        }

        //导出
        if ($_POST['excel'] == 1) {
            $field = '*';
            $order = 'orders.id DESC';
            if ($buttonselect == 'ok') {
                $field .= ',IF(update_time>0, update_time ,payment_time) as u_time';
                $order = 'u_time DESC';
            }
            $order_db->field($field);
            $order_db->order($order);
            $order_db->where($where);
            $orderList = $order_db->select();

            if($_POST['list_measure_excel'] == 1)  //客户尺寸表
                $this->list_measure_excel($orderList);
            if($_POST['order_count_excel'] == 1)   //订单统计表
                $this->order_count_excel($orderList);            
            exit;
        }

        //分页
        $order_db->where($where);
        $count = $order_db->count();//总记录数
        import("ORG.Util.Page");// 导入分页类
        $Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
        $pageShow = $Page->show();// 分页显示输出
        $this->assign('pageShow', $pageShow);
        $nowPage = $Page->getNowPageUrl();//当前页url
        //如果是post过来的则跳转到带参数的url
        if ($_POST && $nowPage) {
            redirect($nowPage);
            exit;
        }
        //保存当前url
        cookie('order_list_nowPage', $nowPage);

        $field = 'id,order_sn,order_amount,pay_amount,order_status,payment_status,is_drawback,
	              shipping_status,delivery_phone,delivery_mobile,delivery_address,
	              delivery_country,delivery_province,delivery_first_name,delivery_last_name,user_id,
	              confirm_time,payment_time,end_time,start_time,is_cheat,language_id,update_time,remark,is_mobile,admin_notes';
		
        $order = 'orders.id DESC';
        if ($buttonselect == 'ok') {
            $field .= ',IF(update_time>0, update_time ,payment_time) as u_time';
            $order = 'u_time DESC';
        }
        $order_db->field($field);
        $order_db->order($order);
        $order_db->limit($Page->firstRow . ',' . $Page->listRows);
        $order_db->where($where);
        $orderList = $order_db->select();

        $language_info = M('language')->field('id,name,name_cn')->select();
        $language = array();
        foreach ($language_info as $k => $v) {//后台显示语言
            $language[$v['id']] = array(
                'name' => $v['name'],
                'name_cn' => $v['name_cn']
            );
        }

        foreach ($orderList as $key => $val) {
            $orderList[$key]['is_size'] = OrderModel::isset_size($val['id']);
        }
		
		$admin_info = $_SESSION['admin_user_info'];
        $this->assign('admin_info', $admin_info);
		
		
        //查询被暂停的订单的数量
        $order_pause = $order_db->where(array('order_status' => OrderModel::ORDER_PAUSE))->count();
        $this->assign('order_pause', $order_pause);

        $yushou_order_type = $post['yushou_order_type'];
        $this->assign('language', $language);
        $this->assign('yushou_order_type', $yushou_order_type);
        $this->assign('orderList', $orderList);
        $this->assign('pageRows', $pageRows);
        if(isset($_REQUEST['is_gift_orders']) && $_REQUEST['is_gift_orders']==1){
            $this->display('gift_order_list');
        }else{
            $this->display('order_list');
        }
    }

    //导出订单统计表
    public function order_count_excel($order_list)
    {   
        //提出国家id
        $country = array();
        foreach ($order_list as $k => $v) {
            $cid = $v['delivery_cid'];
            if( !isset($country[$cid]) ){
               //国家名称
               $countryName = M('region')->where(array('id' => $cid))->getField('name');                
               $country[$cid] =  array(
                'name' => $countryName,
                '2093' => 0,//西服两件套
                '2061' => 0,//西服三件套
                '2104' => 0,//单西
                '2102' => 0,//马夹
                '2103' => 0,//单裤
                '2062' => 0,//衬衫
                '2077' => 0,//领结
                '2106' => 0,//面料卡
                '326'  => 0,//皮尺
                '2076' => 0,//领带
                '2100' => 0,//皮带
                '2098' => 0,//方巾
                '2080' => 0,//领夹
                '2079' => 0,//袖扣
                '328'  => 0,//毛刷
                '2099' => 0,//插片
                '2081' => 0,//领针
                'count'=> 0,//统计
                ); 
            }
        }
        $pidArr = array(326,328); //为了跟上面的分类id区分，单独提出来做判断
        $order_item = D('orders_items');
        $pack_arr = array();
        foreach ($country as $cid=>$res) {
            foreach ($order_list as $k => $v) {
                if($v['delivery_cid'] != $cid) continue;  
                $order_data = array();
                $item_info = $order_item->where('order_id=' . $v['id'])->select();
                foreach ($item_info as $kk => $vv) {
                    $product_id = $vv['product_id']; 
                    $qty = $vv['qty'];
                    if(in_array($product_id, $pidArr)){
                        $country[$cid][$product_id] += $qty;
                        continue; //皮尺 or 毛刷
                    }
                    $catid = D('product')->where(array('id' => $product_id))->getField('catid');
                    if(!isset($country[$cid][$catid])){
                        $catid = D('category')->where(array('id' => $catid))->getField('parentid');  
                    }
                    if(isset($country[$cid][$catid])){
                        $country[$cid][$catid] += $qty;
                        continue;
                    }
                }
            }

            //合计
            $count = 0;
            foreach ($country[$cid] as $num) {
                if (intval($num) > 0){
                    $count += $num;
                }   
            }
            $country[$cid]['count'] = $count;
        }
        //最后一行合计
        $lastCount = array();
        foreach ($country as $cid => $res) {
            foreach ($res as $kk => $vv) {
                if($kk == 'name') {
                    $lastCount['name'] = '合计'; continue;
                }
                if(isset($lastCount[$kk])){
                    $lastCount[$kk] += $vv;
                }else{
                    $lastCount[$kk] = $vv;
                }
            }
        }
        // echo '<pre />';                         
        // print_r($country);exit;
        import('COM.XmlExcel');
        $excel = new XmlExcel;
        $excel_title = array('    ', '西服两件套', '西服三件套', '单西', '马夹', '单裤',
                             '衬衫', '领结', '面料卡', '皮尺', '领带', '皮带', '方巾',
                             '领夹', '袖扣', '毛刷', '插片', '领针', '合计');
        $excel->setSheetHead($excel_title);
        $excel->addRows($country);
        $excel->setSheetHead($lastCount);

        $excel->setSheetHead(array('','','')); //分割行
      
        $height = array(
            array('name'=>'195以上','min'=>195 ,'max'=>100000,'count'=>0),
            array('name'=>'190-194','min'=>190 ,'max'=>194,'count'=>0),
            array('name'=>'185-189','min'=>185 ,'max'=>189,'count'=>0),
            array('name'=>'180-184','min'=>180 ,'max'=>184,'count'=>0),
            array('name'=>'175-179','min'=>175 ,'max'=>179,'count'=>0),
            array('name'=>'170-174','min'=>170 ,'max'=>174,'count'=>0),
            array('name'=>'170以下','min'=>0 ,'max'=>170,'count'=>0),
            array('name'=>'','min'=>0 ,'max'=>0,'count'=>''),
            array('name'=>'','min'=>0 ,'max'=>0,'count'=>''),
            );
        $weight = array(
            array('name'=>'121以上','min'=>121 ,'max'=>100000,'count'=>0),
            array('name'=>'111-120','min'=>111 ,'max'=>120,'count'=>0),
            array('name'=>'101-110','min'=>101 ,'max'=>110,'count'=>0),
            array('name'=>'91-100','min'=>91 ,'max'=>100,'count'=>0),
            array('name'=>'81-90','min'=>81 ,'max'=>90,'count'=>0),
            array('name'=>'71-80','min'=>71 ,'max'=>80,'count'=>0),
            array('name'=>'61-70','min'=>61 ,'max'=>70,'count'=>0),
            array('name'=>'60以下','min'=>0 ,'max'=>60,'count'=>0),
            array('name'=>'','min'=>0 ,'max'=>0,'count'=>''),
            );
        $age =  array(
            array('name'=>'20-24','min'=>20 ,'max'=>24,'count'=>0),
            array('name'=>'25-29','min'=>25 ,'max'=>29,'count'=>0),
            array('name'=>'30-34','min'=>30 ,'max'=>34,'count'=>0),
            array('name'=>'35-39','min'=>35 ,'max'=>39,'count'=>0),
            array('name'=>'40-44','min'=>40 ,'max'=>44,'count'=>0),
            array('name'=>'45-49','min'=>45 ,'max'=>49,'count'=>0),
            array('name'=>'50-59','min'=>50 ,'max'=>59,'count'=>0),
            array('name'=>'60以上','min'=>60 ,'max'=>100000,'count'=>0),
            array('name'=>'19以下','min'=>0 ,'max'=>19,'count'=>0),
            );
        $midArr = array();
        $heightCount = 0;        
        $weightCount = 0;
        $ageCount = 0;
        foreach ($order_list as $k => $v) {
            $item_info = $order_item->where('order_id=' . $v['id'])->select();
            foreach ($item_info as $kk => $vv) {
                $mid = intval($vv['measure_id']);
                if ($mid > 0 && !in_array($mid, $midArr)) {
                    $midArr[] = $mid;
                    $measure = MeasureModel::get_measure_info($mid);
                    $heightCount += $measure['height'];
                    $weightCount += $measure['weight'];
                    $ageCount    += $measure['age'];
                    
                    foreach ($height as $kkk => $vvv) {
                        if( $measure['height'] >= $vvv['min']  && $measure['height'] <= ($vvv['max'] + 1) ){
                            $height[$kkk]['count'] += 1; break;
                        }
                    }                       
                    foreach ($weight as $kkk => $vvv) {
                        if( $measure['weight'] >= $vvv['min']  && $measure['weight'] <= ($vvv['max'] + 1) ){
                            $weight[$kkk]['count'] += 1; break;
                        }
                    }
                    foreach ($age as $kkk => $vvv) {
                        if( $measure['age'] >= $vvv['min']  && $measure['age'] <= ($vvv['max'] + 1) ){
                            $age[$kkk]['count'] += 1; break;
                        }
                    }                                    
                }
            }
        }
        
        $mnum = count($midArr);
        $measureRes = array();
        foreach ($height as $key => $val) {
            $measureRes[] = array(
                                $val['name'],
                                $val['count'],
                                $weight[$key]['name'],
                                $weight[$key]['count'],
                                $age[$key]['name'],
                                $age[$key]['count'],
                            );
        }
        //身型
        $excel_title = array('特殊体型', '正常体型', '平均身高', '平均体重', '平均年龄');
        $excel->setSheetHead($excel_title);
        $excel->setSheetHead(array(
        '',
        '',
        round($heightCount/$mnum,2), 
        round($weightCount/$mnum,2), 
        round($ageCount/$mnum,2)
        ));//分割行

        $excel_title = array('身高(cm)', '人数', '体重(kg)', '人数', '年龄', '人数');
        $excel->setSheetHead($excel_title);
        $excel->addRows($measureRes);

        $excel->setDefaultWidth(100);
        $excel->export('订单统计表' . date('ymdHis'));
    }

    //导出客户尺寸
    public function list_measure_excel($order_list)
    {
        $order_item = D('orders_items');
        $pack_arr = array();
        foreach ($order_list as $k => $v) {
            $order_data = array();
            $item_info = $order_item->where('order_id=' . $v['id'])->select();
            foreach ($item_info as $kk => $vv) {
                $mid = intval($vv['measure_id']);
                if ($mid > 0) {
                    //面料列表
                    $suppliers_id = D('product')->where(array('id' => $vv['product_id']))
                        ->getField('suppliers_id');
                    $suppliers_name = D('suppliers')->where(array('suppliers_id' => $suppliers_id))
                        ->getField('suppliers_name');
                    //如果此订单已经有了此身型的数据就跳出
                    // if(isset($order_data[$mid]) && $order_data[$mid]) {
                    //    $order_data[$mid]['31'] = $order_data[$mid]['31'].' '.$suppliers_name;
                    //    continue;
                    // }
                    $measure = MeasureModel::get_measure_info($mid);
                    if (!$measure) continue;
                    if ($measure['shoulder'] == 1) {
                        $shoulder = "方肩";
                    } elseif ($measure['shoulder'] == 2) {
                        $shoulder = "介于高和正常";
                    } elseif ($measure['shoulder'] == 3) {
                        $shoulder = "正常";
                    } elseif ($measure['shoulder'] == 4) {
                        $shoulder = "介于正常和溜肩";
                    } elseif ($measure['shoulder'] == 5) {
                        $shoulder = "溜肩";
                    } else {
                        $shoulder = '正常';
                    }
                    if ($measure['chest_type'] == 1) {
                        $chest_type = "胸肌发达";
                    } elseif ($measure['chest_type'] == 2) {
                        $chest_type = "介于发达和正常";
                    } elseif ($measure['chest_type'] == 3) {
                        $chest_type = "正常";
                    } elseif ($measure['chest_type'] == 4) {
                        $chest_type = "介于正常和肥胖";
                    } elseif ($measure['chest_type'] == 5) {
                        $chest_type = "厚胸";
                    } else {
                        $chest_type = '正常';
                    }
                    if ($measure['stomach_type'] == 1) {
                        $stomach_type = "平肚";
                    } elseif ($measure['stomach_type'] == 2) {
                        $stomach_type = "介于平腹和微凸";
                    } elseif ($measure['stomach_type'] == 3) {
                        $stomach_type = "正常";
                    } elseif ($measure['stomach_type'] == 4) {
                        $stomach_type = "介于微凸和凸腹";
                    } elseif ($measure['stomach_type'] == 5) {
                        $stomach_type = "凸肚";
                    } else {
                        $stomach_type = '正常';
                    }
                    if ($measure['posture'] == 1) {
                        $posture = "平背";
                    } elseif ($measure['posture'] == 2) {
                        $posture = "微挺";
                    } elseif ($measure['posture'] == 3) {
                        $posture = "正常";
                    } elseif ($measure['posture'] == 4) {
                        $posture = "微驼";
                    } elseif ($measure['posture'] == 5) {
                        $posture = "驼背";
                    } else {
                        $posture = '正常';
                    }

                    $order_data[$mid] = array(
                        '1' => $v['id'],
                        '2' => $vv['product_id'],
                        '3' => $measure['measure_name'],
                        '4' => round($measure['height'], 1),
                        '5' => round($measure['weight'], 1),
                        '6' => $measure['age'],
                        '7' => $shoulder,
                        '8' => $chest_type,
                        '9' => $stomach_type,
                        '10' => $posture,
                        '11' => '&nbsp',
                        '12' => round($measure['neck'], 1),
                        '13' => round($measure['shirt'], 1),
                        '14' => round($measure['chest'], 1),
                        '15' => round($measure['stomach'], 1),
                        '16' => round($measure['pants_hips'], 1),
                        '17' => round($measure['jacket_back'], 1),
                        '18' => round($measure['sleeve'], 1),
                        '19' => round($measure['bicep'], 1),
                        '20' => round($measure['wrist'], 1),
                        '21' => '&nbsp',
                        '22' => round($measure['pants'], 1),
                        '23' => round($measure['waist'], 1),
                        '24' => round($measure['pants_hips'], 1),
                        '25' => round($measure['thigh'], 1),
                        '26' => round($measure['knee'], 1),
                        '27' => '&nbsp',
                        '28' => round($measure['crotch'], 1),
                        '29' => $v['delivery_email'],
                        '30' => $v['delivery_first_name'] . ' ' . $v['delivery_last_name'],
                        '31' => $suppliers_name,
                    );
                }
            }
            foreach ($order_data as $data) {
                $pack_arr[] = $data;
            }
        }
        import('COM.XmlExcel');
        $excel = new XmlExcel;
        $excel_title = array('订单ID', '产品id', '名字', '身高', '体重', '年龄'
        , '肩', '胸', '肚', '背', '号型', '领围', '衣长', '胸围', '腰围', '下摆', '肩宽', '袖长'
        , '袖肥', '袖口', '号型', '裤长', '腰围', '臀围', '横档', '中档', '脚口', '直档', 'Email地址', '收货姓名', '面料编号');
        $excel->setSheetHead($excel_title);
        $excel->addRows($pack_arr);
        $excel->setDefaultWidth(100);
        $excel->export('导出客户尺寸' . date('ymdHis'));
    }

    //发货列表(已确认，已付款，发货未完成)
    public function order_send_list()
    {
        //发货列表
        $where['orders.order_status'] = 1;
        $where['orders.payment_status'] = 1;
        $where['orders.shipping_status'] = array('in', '0,3');

        $order_db = D('orders');

        $pageRows = 20;
        if (isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])) {
            $pageRows = intval($_REQUEST['pageRows']);
        }

        //分页
        $order_db->where($where);
        $count = $order_db->count();//总记录数
        import("ORG.Util.Page");// 导入分页类
        $Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
        $pageShow = $Page->show();// 分页显示输出
        $this->assign('pageShow', $pageShow);

        $order_db->field('id,order_sn,order_amount,pay_amount,order_status,payment_status,shipping_status,delivery_phone,delivery_mobile,delivery_address,delivery_country,delivery_province,delivery_first_name,delivery_last_name,start_time');
        $order_db->order('orders.id DESC');
        $order_db->limit($Page->firstRow . ',' . $Page->listRows);
        $order_db->where($where);
        $orderList = $order_db->select();

        $this->assign('orderList', $orderList);
        $this->assign('pageRows', $pageRows);
        $this->display('order_send_list');
    }

    //导出发货单excel表单
    public function order_send_export_ajax()
    {

    }

    //余额支付
    public function order_surplus_list()
    {
        $where['orders.order_status'] = 1;
        $where['orders.payment_status'] = 1;
        $where['pay_amount'] = 0;
        $order_db = D('orders');

        $pageRows = 20;
        if (isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])) {
            $pageRows = intval($_REQUEST['pageRows']);
        }

        //分页
        $order_db->where($where);
        $count = $order_db->count();//总记录数
        import("ORG.Util.Page");// 导入分页类
        $Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
        $pageShow = $Page->show();// 分页显示输出
        $this->assign('pageShow', $pageShow);

        $order_db->field('id,order_sn,order_amount,pay_amount,order_status,payment_status,shipping_status,delivery_phone,delivery_mobile,delivery_address,delivery_country,delivery_province,delivery_first_name,delivery_last_name,start_time');
        $order_db->order('orders.id DESC');
        $order_db->limit($Page->firstRow . ',' . $Page->listRows);
        $order_db->where($where);
        $orderList = $order_db->select();

        $this->assign('orderList', $orderList);
        $this->assign('search', null);
        $this->assign('clear', null);
        $this->assign('pageRows', $pageRows);
        $this->display('order_list');
    }

    //编辑订单
    public function order_edit()
    {
        $order_id = intval($_GET['oid']);

        //欺诈对比
        OrderModel::orderCheckCheat($order_id);

        $orderInfo = OrderModel::getOrderInfo($order_id);
        if (!$orderInfo) {
            $this->error('订单不存在！', U('order/order_list'));
        }

        if (isset($_POST['dosubmit']) && $_POST['dosubmit']) {//var_dump($_POST);die;
            $order_db = D('orders');

            //if(in_array($orderInfo['order_status'], array(OrderModel::ORDER_COMPLETE, OrderModel::ORDER_CANCELED, OrderModel::ORDER_DEL)))
            if (in_array($orderInfo['order_status'], array(OrderModel::ORDER_DEL))) //OrderModel::ORDER_COMPLETE,
            {
                $this->error('订单已经完成，不能修改', U('order/order_list'));
            }

            $payment_status = $_POST['payment_status'];
            $shipping_status = $_POST['shipping_status'];
            $order_status = $_POST['order_status'];
            if ($shipping_status != OrderModel::SHIPPING_UNSHIPPED) {
                if ($order_status == OrderModel::ORDER_UNCONFIRMED || $order_status == OrderModel::ORDER_DEL || $payment_status == OrderModel::PAY_UNPAYED) {
                    $this->error('订单已经删除、未确认或者未支付，不能送货', U('order/order_edit', array('oid' => $order_id)));
                }
            }

            //客服填写的特殊要求
            if ($_POST['special_request']) {
                $order_items_db = M('orders_items');
                foreach ($_POST['special_request'] as $k => $v) {
                    if (isset($v) && !empty($v)) {
                        $data = array();
                        $data['id'] = $k;
                        $data['special_request'] = $v;
                        $order_items_db->save($data);
                    }
                }
            }
            //已发货(部分发)时间
//			if(($shipping_status == OrderModel::SHIPPING_SHIPPED || $shipping_status == OrderModel::SHIPPING_SHIPPED_PART) && $shipping_status != $orderInfo['shipping_status'])
//			{
//				$_POST['shipping_time'] = time();
//			}
            //设置支付时间
            if ($payment_status == OrderModel::PAY_PAYED && $payment_status != $orderInfo['payment_status']) {
                $_POST['payment_time'] = time();
                $order_status = OrderModel::ORDER_CONFIRMED;
                //赠送全部积分
                OrderModel::sendOrderPoints($order_id);
            } elseif ($payment_status == OrderModel::PAY_FULL_REFUND || $payment_status == OrderModel::PAY_PARTIAL_REFUND) {
                $order_status = OrderModel::ORDER_COMPLETE;
            }

            //确认订单时间
            if ($order_status == OrderModel::ORDER_CONFIRMED && $order_status != $orderInfo['order_status']) {
                $_POST['confirm_time'] = time();
            }
            if ($order_status == OrderModel::ORDER_COMPLETE) {
                $_POST['end_time'] = time();

            }

            $_POST['order_status'] = $order_status;

            //更新订单
            OrderModel::update_order($order_id, $_POST);
            //好友推荐送余额
            if($_POST['order_status']==OrderModel::ORDER_CONFIRMED&&$_POST['payment_status']==OrderModel::PAY_PAYED &&$orderInfo['product_amount']>=300){
                if($orderInfo['user_id']){
                    $user_email=D("users")->where(array('id'=>$orderInfo['user_id']))->getField("email");
                    UserModel::get_money_friend($orderInfo['id'],$user_email);
                }
            }

            //添加订单日志
            $logData = array(
                'order_id' => $orderInfo['id'],
                'order_status' => $order_status,
                'payment_status' => $payment_status,
                'shipping_status' => $shipping_status,
                'action_notice' => $_POST['action_notice'] ? trim($_POST['action_notice']) : null,
            );
            OrderModel::insertOrdersLog($logData);
            //TODO

            //订单完成或者取消，订单清算
            if ($order_status == OrderModel::ORDER_COMPLETE || $order_status == OrderModel::ORDER_CANCELED) {
                //如果支付
                if ($payment_status != OrderModel::PAY_UNPAYED) {
                    //全部退款或者退货
                    if ($payment_status == OrderModel::PAY_FULL_REFUND || $shipping_status == OrderModel::SHIPPING_RETURNED) {
                        //全额退积分,退款
                        OrderModel::returnedOrderALLPoints($order_id);
                    } else {
                        OrderModel::returnedPartOrderPoints($order_id);
                    }
                }
                //订单取消退回支付使用的积分和余额
                if ($order_status == OrderModel::ORDER_CANCELED) {
                    OrderModel::returnedOrderSurplusANDPoints($order_id);
                }
            }


            //已发货(部分发)
//			if(($shipping_status == OrderModel::SHIPPING_SHIPPED || $shipping_status == OrderModel::SHIPPING_SHIPPED_PART) && $shipping_status != $orderInfo['shipping_status'])
//			{
//				$email_template = UserModel::getEmailTemplateInfo('orderTradingEmail', $orderInfo['language_id']);
//			}
            $ShortMessage=A("ShortMessage");
            //支付成功通知短信
            if ($payment_status == OrderModel::PAY_PAYED && $payment_status != $orderInfo['payment_status']) {
                //$email_template = UserModel::getEmailTemplateInfo('orderPayEmail', $orderInfo['language_id']);
                $short_mesg_result=$ShortMessage->send_message('SMS_4725607',$orderInfo['delivery_phone'],'{"order_sn":"'.$orderInfo['order_sn'].'"}');
               // if($short_mesg_result){
                    Log::write('支付短信，订单号'.$orderInfo['order_sn'].'，后台操作，订单金额：'.$orderInfo['order_amount'].'，时间：'.date("Y-m-d H:i:s",time()));
               // }
            } elseif ($order_status == OrderModel::ORDER_COMPLETE&& $order_status  != $orderInfo['order_status']) {//订单完成短信
                $short_mesg_result=$ShortMessage->send_message('SMS_4690564',$orderInfo['delivery_phone'],'{"order_sn":"'.$orderInfo['order_sn'].'"}');
              //  if($short_mesg_result){
                    Log::write('订单完成短信，订单号：'.$orderInfo['order_sn'].'，时间：'.date("Y-m-d H:i:s",time()));
               // }
            }
            //取货通知
            if( $shipping_status!=$orderInfo['shipping_status']&&$shipping_status==OrderModel::SHIPPING_SHIPPED&&$_POST['shipping_method']=="ziqu"){
                $short_mesg_result=$ShortMessage->send_message('SMS_4750632',$orderInfo['delivery_phone'],'{"order_sn":"'.$orderInfo['order_sn'].'","get_time":"10:00-22:30","our_address":"杭州市西湖区教工路158-2号"}');
              //  if($short_mesg_result){
                    Log::write('取货通知短信，订单号：'.$orderInfo['order_sn'].'，时间：'.date("Y-m-d H:i:s",time()));
              //  }
            }
           //发送取消订单邮件
           /* elseif ($order_status == OrderModel::ORDER_CANCELED) {
                $email_template = UserModel::getEmailTemplateInfo('orderCancelEmail', $orderInfo['language_id']);
            }*/
           /* if ($email_template) {
                $mailInstance = D(WEB_APP_NAME . '://Email');
                $content = $mailInstance->replaceMail($email_template['content'], $orderInfo);
                $title = $mailInstance->replaceMail($email_template['title']);
                $mailInstance->sendMail($orderInfo['delivery_email'], $title, $content);
            }*/

            if ($order_status == OrderModel::ORDER_DEL || $order_status == OrderModel::ORDER_CANCELED) {
                //查询订单子数据
                $product = OrderModel::getOrderProductList($order_id); //订单产品列表        
                //给配件商品增加库存
                foreach ($product as $key => $val) {

                    $where_inventory = array(
                        'order_item_id' => $val['id'],
                        'change' => 0,
                    );
                    $inventory = D('inventory')->where($where_inventory)->select();

                    foreach ($inventory as $kk => $vv) {
                        //库存用料记录复原
                        $addPost = array(
                            'type' => $vv['type'],
                            'tid' => $vv['tid'],
                            'order_sn' => $vv['order_sn'],
                            'order_id' => $vv['order_id'],
                            'order_item_id' => $vv['order_item_id'],
                            'pid' => $vv['pid'],
                            'amount' => $vv['amount'],
                            'remark' => '订单取消或者删除, 库存恢复',
                        );
                        $res = SuppliersModel::inventoryAdd($addPost);
                    }
                }
            }
            //取缓存里的返回地址
            $goUrl = cookie('order_list_nowPage') ? cookie('order_list_nowPage') : U('order/order_list');
            cookie('order_list_nowPage', null);
            $this->success('订单修改成功！', $goUrl);
            /*//echo '<script>setTimeout("history.go(-2)",1000);</script>';*/
        } else {
            $orderInfo['product'] = OrderModel::getOrderProductList($order_id); //订单产品列表
            //var_dump($orderInfo);die;
            $orderInfo['logs'] = OrderModel::getOrdersLogList($order_id); //订单日志
            $orderInfo['shipping_no'] = OrderModel::getShippingNumber($order_id);
            $orderInfo['deliveryCount'] = OrderModel::getDeliveryCount($order_id);//判断有没有配货单
            $orderInfo['deliveryHavingDeliverying'] = OrderModel::getHavingDelivery($order_id);//判断是否须要配货
			if(isset($orderInfo['product']) && $orderInfo['product']){
				foreach($orderInfo['product'] as &$oval){ 
					 $oval['code_show'] = preg_match('/绣字第一行/', $oval['attr']) ? 1 :0;
					 $oval['code_shows'] = preg_match('/绣字:/', $oval['attr']) ? 1 :0;
				}
			}
            $this->assign('order', $orderInfo);

            if ($orderInfo['coupon_code']) {
                $coupon_info = M('favorable')->field('status,coupon_money,type')->where("coupon_code='" . $orderInfo['coupon_code'] . "'")->find();
                if ($coupon_info['status'] == 4 || $coupon_info['type'] == 4) {//折扣优惠码
                    $this->assign('coupon_info', $coupon_info);
                }
            }

            //国家列表
            $countryList = SiteModel::getCountryList();
            $this->assign('countryList', $countryList);
//			//省市列表
//			$provinceList = null;
//			if($orderInfo['delivery_cid']){
//				$userAction = new UserAction();
//				$provinceList = $userAction->public_area_ajax($orderInfo['delivery_cid'],0);
//			}
//			$this->assign('provinceList', $provinceList);
            //会员信息
            $userInfo = UserModel::getUserInfo($orderInfo['user_id']);
            $this->assign('user', $userInfo);

            $paymentList = PaymentModel::getPaymentList(); //支付方式列表
            $shippingList = ShippingModel::getShippingList(); //配送方式列表
            $this->assign('paymentList', $paymentList);
            $this->assign('shippingList', $shippingList);


            //设计师列表
            $designerList = UserModel::getUserDesignerList();
            $this->assign('designerList', $designerList);
            $this->assign('orderInfo', $orderInfo);
            $this->display('order_edit');
        }
    }
	
	//修改订单属性
	public function eidt_order_attribute($order_item_id,$measure_id,$type){
		$order_item_res = D("orders_items")->where(array("id"=>$order_item_id))->find();
		$measure_res    = D("user_measure")->where(array("id"=>$measure_id))->find();
		if($order_item_id && $measure_id && !empty($order_item_res) && !empty($measure_res)){
			$productInfo = ProductModel::get_product_info($order_item_res['product_id']);
			if($productInfo['attribute_type'] != 2 || !$productInfo){
				exit("产品不存在！");
			}
			$data['productInfo'] = $productInfo;
			$attrData = $order_item_res['attr']; 
			list($attributeList, $size_type, $attrOptionArr) = CartModel::cart_attr_show($order_item_res['product_id'], $attrData,$measure_res['sid'], true);
			if(in_array($productInfo['id'],C('clear_xiuzi_id'))||in_array($productInfo['catid'],C('clear_xiuzi_catid'))){
				$attrOptionArr['fontLocation'] = 0;
				unset($attributeList[9999]);
			}
			$buy_type = 0;
			//cid>0的情况下，查询是否选尺码购买
			if($order_item_res['measure_id']>0 && $productInfo['model_id'] != 25){
				$measure = MeasureModel::get_measure_one(array('id' => $order_item_res['measure_id']));
				if($measure['m_status'] == 5){
					$buy = 'now'; //属于快速购买
					$this->assign('msizedata', base64_encode($measure['measure_data'])); 
				}
			}
			
			$this->assign('custom_more', $attrOptionArr['custom_more']);
        	$this->assign('sel_custom_val', $measure_res['sid']);
			foreach($attributeList as &$val){
				if(is_array($val['values'])){
					foreach($val['values'] as $v){
						if($v['product_attr_id']==$val['default']){
							$val['mo_default'] = $v['attr_value_id'];	
						}
					}
				}
			}
			
			$this->assign('attributeList', isset($attributeList) ? $attributeList : null);
			$this->assign('arrtlist', $attrOptionArr['arrtlist']);
			//鞋子的尺码
			$shoe_size=ProductModel::get_shoes_size_data($productInfo['shoes_size_max'],$productInfo['shoes_size_min'],$productInfo['shoes_size_del']);
        	$this->assign('shoe_size', $shoe_size);
			
			$show_attr_array=array();
			if($productInfo['show_attr_ids']){
				$show_attr_array=explode(",",$productInfo['show_attr_ids']);
			}
			//$customArrayCache = unserialize(base64_decode(session('custom_admin')));print_r($customArrayCache);exit;
			$this->assign("show_attr_array",$show_attr_array);
			$this->assign("type",$type);
			$this->assign($data);
			$this->assign("order_item_res",$order_item_res);
			$this->assign("measure_res",$measure_res);
			$this->display("eidt_order_attribute");
		}else{
			exit("数据出错！");
		}
	}
	
	public function edit_order_attribute_do(){
		$arr=array("code"=>"error","message"=>"操作失败");
		if($_POST){
			if(isset($_POST['order_item_id'])){
				$order_item_id = I("order_item_id",'','intval');
				$order_item_res = D("orders_items")->where(array("id"=>$order_item_id))->find();
				$cache_custom=session('custom_admin');
				
				$customArray = unserialize(base64_decode($cache_custom));
				//print_r($customArray);exit;
				$new_arr=array();
				if(is_array($customArray) && is_array($customArray[$order_item_res['product_id']])){
					foreach($customArray[$order_item_res['product_id']] as $val){
						$val_Arr = explode(':', $val);
						$new_arr[]=array("attr_id"=>$val_Arr[0],"attr_name"=>$val_Arr[1],"product_attr_id"=>$val_Arr[2],"attr_value"=>$val_Arr[3],"attr_value_id"=>$val_Arr[4]);
					}
				}
				
				if(count($new_arr)>0){
					if(D("orders_items")->where(array("id"=>$order_item_id))->save(array("attr"=>serialize($new_arr)))){
						$result=$this->getResults($new_arr,unserialize($order_item_res['attr']));
						
						$order=D("orders")->where(array("id"=>$order_item_res['order_id']))->find(); 
						//添加订单日志
						$logData = array(
							'order_id' => $order_item_res['order_id'],
							'order_status' => $order['order_status'],
							'payment_status' => $order['payment_status'],
							'shipping_status' => $order['shipping_status'],
							'action_notice' => $result,
						);
						OrderModel::insertOrdersLog($logData);
						$arr=array("code"=>"200","message"=>"操作成功！");
					}
				}
			}
		}
		echo json_encode($arr);exit;
	}
	
	public function getResults($new_arr,$old_arr){
		$content="";
		foreach($new_arr as $k=>$v){
			foreach($old_arr as $key=>$val){
				if($v['attr_id']==$val['attr_id']){
					if(in_array($v['attr_id'],array(54,70,112,134))){
						if($v['attr_value_id']==$val['attr_value_id']){
							if($v['product_attr_id']!=$val['product_attr_id']){
								$content.="属性:".$val['attr_name']."由".$val['attr_value'].'改为'.$v['attr_value']."<br/>";
							}
						}
					}else{
						if($v['attr_value']!=$val['attr_value']){
							$content.="属性:".$val['attr_name']."由".$val['attr_value'].'改为'.$v['attr_value']."<br/>";	
						}	
					}
				}
			}
		}
		return $content;
	}
	
	public function edit_attr_code(){
		$id = I("get.item_id","","intval");
		$content = D("orders_items")->find($id);
		$font_1= preg_match('/绣字第一行/', $content['attr']) ? 1 :0;
		$font_2= preg_match('/绣字第二行/', $content['attr']) ? 1 :0;
		$font= preg_match('/绣字"/', $content['attr']) ? 1 :0;
		
		$data=unserialize($content['attr']);
		
		$font_value =$font_1_value = $font_2_value ="";
		foreach($data as $v){
			if($v['attr_name']=="绣字第一行"){
				$font_1_value=$v['attr_value'];
			}
			if($v['attr_name']=="绣字第二行"){
				$font_2_value=$v['attr_value'];
			}
			if($v['attr_name']=="绣字"){
				$font_value=$v['attr_value'];
			}
		}
		if($_POST){
			foreach($data as &$v){
				if($v['attr_name']=="绣字第一行"){
					$v['attr_value']=I("post.font_1_value","","trim");
				}
				if($v['attr_name']=="绣字第二行"){
					$v['attr_value']=I("post.font_2_value","","trim");
				}
				if($v['attr_name']=="绣字"){
					$v['attr_value']=I("post.font_value","","trim");
				}
			}
			$date['attr']=serialize($data);
			
			if(D("orders_items")->where(array("id"=>$id))->save($date)){
				$this->success('操作成功');
			}else{
				$this->error('操作失败');	
			}
		}
		$this->assign("id",$id);
		$this->assign("font",$font);
		$this->assign("font_1",$font_1);
		$this->assign("font_2",$font_2);
		$this->assign("font_value",$font_value);
		$this->assign("font_1_value",$font_1_value);
		$this->assign("font_2_value",$font_2_value);
		
		$this->display('edit_attr_code');	
	}
	
    //TODO 暂时不需要,添加订单
    public function order_add()
    {
        $step = $_GET['step'] ? $_GET['step'] : 'user';
        if ($step == 'user') {

        } elseif ($step = 'user_add') {

        }
        $this->assign('step', $step);
        $this->display('order_add');
    }

    //发货单列表
    public function order_delivery_list()
    {
        $order_db = D('orders');
        $post = array_merge($_GET, $_POST);
        $order_id = intval($post['oid']);
        $order_sn = $post['order_sn'];
        if ($order_sn) {
            $order_id = $order_db->where(array('order_sn' => $order_sn))->getField('id');
        }
        $where = array();
        if ($order_id) {
            $where['orders_delivery.order_id'] = $order_id;
            $this->assign('order_sn', $post['order_sn']);
        }
        if ($post['delivery_sn']) {
            $where['orders_delivery.delivery_sn'] = $post['delivery_sn'];
            $this->assign('delivery_sn', $post['delivery_sn']);
        }
        if ($post['shipping_no']) {
            $where['orders_delivery.shipping_no'] = $post['shipping_no'];
            $this->assign('shipping_no', $post['shipping_no']);
        }
        if ($post['status']) {
            $where['orders_delivery.status'] = intval($post['status']);
            $this->assign('status', intval($post['status']));
        }

        $pageRows = 20;
        if (isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])) {
            $pageRows = intval($_REQUEST['pageRows']);
        }

        $order_delivery_db = D('orders_delivery');
        //分页
        $order_delivery_db->where($where);
        $count = $order_delivery_db->count();//总记录数
        import("ORG.Util.Page");// 导入分页类
        $Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
        $pageShow = $Page->show();// 分页显示输出
        $this->assign('pageShow', $pageShow);
        $nowPage = $Page->getNowPageUrl();//当前页url
        //如果是post过来的则跳转到带参数的url
        if ($_POST) {
            redirect($nowPage);
            exit;
        }
        //保存当前url
        cookie('order_delivery_list_nowPage', $nowPage);

        $order_delivery_db->field('orders_delivery.*,orders.order_sn,orders.start_time');
        $order_delivery_db->join('orders ON orders.id = orders_delivery.order_id');
        $order_delivery_db->limit($Page->firstRow . ',' . $Page->listRows);
        $order_delivery_db->where($where);
        $order_delivery_db->order('orders_delivery.add_time DESC');
        $deliveryList = $order_delivery_db->select();

        $this->assign('deliveryList', $deliveryList);
        $this->assign('pageRows', $pageRows);
        $this->display('order_delivery_list');
    }

    //发货单信息
    public function order_delivery_edit()
    {//var_dump($_REQUEST);die;
        $order_id = intval($_GET['oid']);
        $delivery_id = intval($_GET['did']);
        $orderInfo = OrderModel::getOrderInfo($order_id);
        $deliveryInfo = OrderModel::getDeliveryInfo($delivery_id);

        if ($_GET['emaiid']) {
            $orderInfo['shipping_no'] = $_GET['shippingno'];

            /*此发货单邮件*/
            $orderInfo['delivery_sn'] = $deliveryInfo['delivery_sn'];
            $orderInfo['shipping_no'] = $_GET['shippingno'];
            $orderInfo['shipping_time'] = $deliveryInfo['update_time'] ? $deliveryInfo['update_time'] : $deliveryInfo['add_time'];
            $orderInfo['deliveryList'] = OrderModel::getDeliveryProductList($order_id, $delivery_id);
        }

        if ($_POST['dosubmit']) {
            $order_delivery_db = D('orders_delivery');
            if (isset($_POST['cancel']) && $_POST['cancel']) {
                $data = array(
                    'status' => 1,
                    'shipping_no' => '',
                    'update_time' => '',
                );
                $order_delivery_db->where('id=' . $delivery_id)->save($data);
                $shipping_status = 0;
            } else {
                $data = array(
                    'status' => 2,
                    'shipping_no' => trim($_POST['shipping_no']),
                    'update_time' => time(),
                );
                $order_delivery_db->where('id=' . $delivery_id)->save($data);
                //更改发货状态
                OrderModel::updateDeliveryStatus($order_id);

                //通知短信
                $orderInfo['delivery_sn'] = $deliveryInfo['delivery_sn'];
                $orderInfo['shipping_no'] = $_POST['shipping_no'];
                //$orderInfo['shipping_time'] = $deliveryInfo['update_time'] ? $deliveryInfo['update_time'] : $deliveryInfo['add_time'];
               // $orderInfo['shipping_time'] = time(); //20150410 为了分开配货时间和发货时间
              //  $orderInfo['deliveryList'] = OrderModel::getDeliveryProductList($order_id, $delivery_id);
                $order_db = D('orders');
                $order_db->where('id=' . $order_id)->save(array('shipping_time' => $orderInfo['shipping_time'], 'shipping_no' => $_POST['shipping_no']));
                $ShortMessage=A("ShortMessage");
                //取货通知
                if($orderInfo['shipping_method']=="ziqu"){
                    $short_mesg_result=$ShortMessage->send_message('SMS_4750632',$orderInfo['delivery_phone'],'{"order_sn":"'.$orderInfo['order_sn'].'","get_time":"10:00-22:30","our_address":"杭州市西湖区教工路158-2号"}');
                   // if($short_mesg_result){
                        Log::write('取货通知短信，订单号：'.$orderInfo['order_sn'].'，时间：'.date("Y-m-d H:i:s",time()));
                   // }
                }else{//发货通知
                    $address=$orderInfo['delivery_province'].$orderInfo['delivery_city'].$orderInfo['delivery_address'].$orderInfo['delivery_address2'];
                    $str_short_message='{"order_sn":"'.$orderInfo['order_sn'].'","shipping_num":"'.$orderInfo['shipping_no'].'","address":"'.$address.'"}';
                    $short_mesg_result=$ShortMessage->send_message("SMS_4785493", $orderInfo['delivery_phone'],$str_short_message);
                   // if($short_mesg_result){
                        Log::write('发货通知短信，订单号：'.$orderInfo['order_sn'].'，时间：'.date("Y-m-d H:i:s",time()));
                   // }
                }
                
                if ($orderInfo['shipping_status'] == OrderModel::SHIPPING_SHIPPED_PART) {
                    $shipping_status = $orderInfo['shipping_status'];
                } else {
                    $shipping_status = 1;
                }
            }

            //添加日志
            $logData = array(
                'order_id' => $orderInfo['id'],
                'order_status' => $orderInfo['order_status'],
                'payment_status' => $orderInfo['payment_status'],
                'shipping_status' => $shipping_status,
                'action_notice' => $_POST['action_notice'] ? trim($_POST['action_notice']) : null,
            );

            OrderModel::insertOrdersLog($logData);
            //给配件商品减去库存
            foreach ($orderInfo['deliveryList'] as $key => $val) {
                $catid = D('product')->where(array('id' => $val['product_id']))->getField('catid');
                if ($catid != 2067) {
                    $parentid = D('category')->where(array('id' => $catid))->getField('parentid');
                    if ($parentid != 2067) continue;
                }
                //库存用料记录
                $addPost = array(
                    'type' => 2,
                    'tid' => $val['product_id'],
                    'order_sn' => $orderInfo['order_sn'],
                    'order_id' => $val['order_id'],
                    'order_item_id' => $val['id'],
                    'pid' => $val['product_id'],
                    'amount' => -$val['send_number'],
                );
                $res = SuppliersModel::inventoryAdd($addPost);
            }

            $this->redirect(U('order/order_delivery_list'));
        } else {
            $orderInfo['productList'] = OrderModel::getDeliveryProductList($order_id, $delivery_id); //订单产品列表
            $orderInfo['logs'] = OrderModel::getOrdersLogList($order_id); //订单日志
            $this->assign('order', $orderInfo);
            $this->assign('delivery', $deliveryInfo);
            $this->display('order_delivery_edit');
        }
    }
    
    //删除配货
    public function order_delivery_del(){
        $did =  intval($_REQUEST['did']);
        D('orders_delivery')->where(array('id'=>$did))->delete();
        D('orders_delivery_product')->where(array('orders_delivery_id'=>$did))->delete();
        //取缓存里的返回地址
        $goUrl = cookie('order_delivery_list_nowPage') ? cookie('order_delivery_list_nowPage') : U('order/order_list');
        cookie('order_delivery_list_nowPage', null);
        $this->success('订单修改成功！', $goUrl);
    }

    //添加配货修改
    public function order_delivery_add()
    {
        $order_id = intval($_GET['oid']);
        $orderInfo = OrderModel::getOrderInfo($order_id);
        if (!$orderInfo) {
            $this->error('订单不存在！', U('order/order_list'));
        }

        if (in_array($orderInfo['order_status'], array(OrderModel::ORDER_COMPLETE, OrderModel::ORDER_CANCELED, OrderModel::ORDER_DEL))) {
            $this->error('订单已经完成，不能修改', U('order/order_list'));
        }
        $productList = OrderModel::getOrderDeliveryProductList($order_id); //订单产品列表

        if ($_POST['dosubmit']) {
            if (!$productList) {
                $this->error('订单无商品');
            }
            $post = $_POST['send'];
            foreach ($post as $key => $send) {
                if (empty($send['id']) || $send['number'] == 0) {
                    unset($post[$key]);
                }
            }
            if (empty($post)) {
                $this->error('未选择配货商品', U('order/order_edit', 'oid=' . $order_id));
            }


            $order_delivery_db = D('orders_delivery');
            $order_delivery_product_db = D('orders_delivery_product');

            //入库发货单
            $data = array(
                'delivery_sn' => OrderModel::getDeliverySn(),
                'order_id' => $order_id,
                'add_time' => time(),
                'action_user' => $_SESSION['admin_user_info']['user_name'],
                'shipping_no' => $shipping_no,
                'status' => 1,
                'update_time' => time(),
            );
            $delivery_id = $order_delivery_db->add($data);

            //发货单商品列表
            foreach ($productList as $item) {
                //商品要发货
                $send_number = intval($post[$item['id']]['number']);
                if (isset($post[$item['id']]['id']) && $send_number && $item['stock']) {
                    //如果填写的发货数大于要发货的数量
                    if ($send_number > ($item['qty'] - $item['send_number'])) {
                        $send_number = $item['qty'] - $item['send_number'];
                    }
                    //如果大于库存
                    if ($send_number > $item['stock']) {
                        $send_number = $item['stock'];
                    }

                    //发货单商品
                    if ($delivery_id) {
                        $pro_data = array(
                            'orders_delivery_id' => $delivery_id,
                            'orders_items_id' => $item['id'],
                            'send_number' => $send_number,
                        );
                        $order_delivery_product_db->add($pro_data);
                    }
                }
            }
            
            //20150624 以生产部设置用户身型记录第一次保存 设置 配货中状态
            // //添加订单日志
            // $logData = array(
            //     'order_id' => $orderInfo['id'],
            //     'order_status' => $orderInfo['order_status'],
            //     'payment_status' => $orderInfo['payment_status'],
            //     'shipping_status' => 99,//配货中
            //     'action_notice' => $_POST['action_notice'] ? trim($_POST['action_notice']) : null,
            // );
            // OrderModel::insertOrdersLog($logData);

            $this->success('操作成功');// ,U('order/order_delivery_list', 'oid='.$order_id)
            echo '<script>setTimeout("history.go(-3)",1000);</script>';
        } else {
            $orderInfo['productList'] = $productList;
            $this->assign('order', $orderInfo);
            $this->display('order_delivery_add');
        }
    }

    //订单打印
    public function order_print()
    {
        $order_id = intval($_GET['oid']);
        $orderInfo = OrderModel::getOrderInfo($order_id);
        if (!$orderInfo) {
            $this->error('订单不存在！', U('order/order_list'));
        }
        $userInfo = UserModel::getUserInfo($orderInfo['user_id']);
        $orderInfo['product'] = OrderModel::getOrderProductList($order_id); //订单产品列表
        $this->assign('order', $orderInfo);
        $this->assign('user', $userInfo);
        if ($orderInfo['measure_data']) {
            $this->display('order_print02');
        } else {
            $this->display('order_print');
        }
    }

    //订单打印
    public function order_print_figure_god()
    {
        $order_item_id = intval($_GET['order_item_id']);
        $order_items_db = D('orders_items');
        $order_item_info = $order_items_db->find($order_item_id);
        $this->assign('order', $order_item_info);
        //打印不显示
        $this->assign('noshow', intval($_GET['noshow']));
        //收货姓名
        $this->assign('name',$_GET['name']);
        //用户的身形数据
        $user_measure = D('user_measure');
        $measure = $user_measure->where(array('id' => $order_item_info['measure_id']))->find();

        //*******************
        //获取身型字段 兼容原先代码
        if ($measure) {
            $measure_field = MeasureModel::user_measure_field();
            foreach ($measure_field as $key => $val) {
                $value = $measure[$val['measure_field']];
                if ($val['measure_field'] == 'age') {
                    $new_measure_data[$val['measure_field']] = $value;
                } else if ($val['measure_field'] == 'chest_type') {
                    $new_measure_data['chest'][$val['field_type']] = $value;
                } else if ($val['measure_field'] == 'stomach_type') {
                    $new_measure_data['stomach'][$val['field_type']] = $value;
                } else {
                    $new_measure_data[$val['measure_field']][$val['field_type']] = $value;
                }
            }
            $measure['measure_data'] = serialize($new_measure_data);
        }
        //********************
        $this->assign('measure', $measure);
        //商品类型
        $orderfigure = OrderModel::orderPrintFigure($order_item_id);
        $arr = $orderfigure['attributes_more_array'];
        //dump($orderfigure);exit;

        $orderfigure['attr_array']['90'] ? $this->assign('key', 90) : $this->assign('key', 111);

        //$lining_db = D('lining');
        //$lining_info = $lining_db->where(array('suppliers_name'=>$orderfigure['attr_array'][$key]['cn_attr_value_name']))->find();
        //$this->assign('lining',$lining_info);
        //订单号
        $order = M('orders');
        $orderInfo = $order->where(array('id'=>$orderfigure['order_id']))->find();
        //$this->assign('orderNum',$orderNum);
        $this->assign('order_item_id', $order_item_id);
        //商品两件套或三件套或衬衫类型
        $product_db = D('product');
        $product_info = $product_db->where(array('id' => $order_item_info['product_id']))->find();
        //dump($product_info);exit;

        list($font_1_key, $font_2_key, $font_zt_key, $font_color_key) = OrderModel::font_key($orderfigure, $product_info['model_id']);
        $font_1 = isset($orderfigure['attr_array'][$font_1_key]) ? $orderfigure['attr_array'][$font_1_key]['cn_attr_value_name'] : '';  //第一行
        $font_2 = isset($orderfigure['attr_array'][$font_2_key]) ? $orderfigure['attr_array'][$font_2_key]['cn_attr_value_name'] : '';  //第二行
        $font_zt = isset($orderfigure['attr_array'][$font_zt_key]) ? $orderfigure['attr_array'][$font_zt_key]['cn_attr_value_name'] : '';  //绣字字体
        $font_color = isset($orderfigure['attr_array'][$font_color_key]) ? $orderfigure['attr_array'][$font_color_key]['cn_attr_value_name'] : '';  //绣字颜色
        if (!$font_1 && !$font_2) {
            $font_zt = '';
            $font_color = '';
            unset($orderfigure['attr_array'][$font_1_key]);
            unset($orderfigure['attr_array'][$font_2_key]);
            unset($orderfigure['attr_array'][$font_zt_key]);
            unset($orderfigure['attr_array'][$font_color_key]);
        }

        $this->assign('font_1', $font_1);
        $this->assign('font_2', $font_2);
        $this->assign('font_zt', $font_zt);
        $this->assign('font_color', $font_color);

        //打印字体    
        if ($_GET['font'] == '1') {
            $this->display('order_print_font_n1');
            exit;
        }
		$suppliers_info = array();
		$suppliers_db = D('suppliers');
        //1219，1220，1221  3D模块处理
		if($product_info['id']==1878 || $product_info['id']==1879 || $product_info['id']==1880 || $product_info['id']==1881){
			$extension_attr_info=unserialize($order_item_info['attr']);
			foreach($extension_attr_info as $ek=>$ev){
                if($ev['attr_id']==253 || $ev['attr_id']==259 || $ev['attr_id']==269){
                    $suppliers_name = $ev['attr_value'];
                    $suppliers_info = $suppliers_db->where(array('suppliers_name' => $suppliers_name))->find();
                }
			}
		}
        //面料列表
		if(empty($suppliers_info)){
            $suppliers_info = $suppliers_db->where(array('suppliers_id' => $product_info['suppliers_id']))->find();
        }
        $this->assign('suppliers', $suppliers_info);

        $special_request = "";
        //获取用户特殊需求
        if($orderInfo['user_id']){
            $userInfo = UserModel::getUserInfo($orderInfo['user_id']);        
            $special_request .= $userInfo['require'];
        }
        //件数和单裤备注        
        if ($orderfigure['qty'] > 1) {
            $special_request .= "<b>制作:" . $orderfigure['qty'] . "件</b><br />";
        }
        if ($orderfigure['pants_qty'] > 0) {
            $special_request .= "<b>加同款单裤:" . $orderfigure['pants_qty'] . "条</b><br />";
        }
        if ($suppliers_info['is_lined'] == 1) {
            $special_request .= "<b>半麻衬</b><br />";
        }
        $orderfigure['special_request'] = $special_request . $orderfigure['special_request'];

        //分类属性名称
        $orderfigure['categoryName'] = "";
        $category_id_arr = explode(',', $product_info['category_id']);
        foreach ($category_id_arr as $category_id) {
            $category_name = CategoryModel::getCategoryItems($category_id, C('language_id'));
            $orderfigure['categoryName'] .= $category_name[C('language_id')]['name'] . ' ';
        }
        //商品的纽扣名称
        if ($product_info['model_id'] == 1) { //单西取定制选项里的纽扣
            $orderfigure['button_name'] = $orderfigure['attr_array'][150]['cn_attr_value_name'];
        } else {
            $orderfigure['button_name'] = $product_info['button_name'];
        }
        

        //取配置项里的类别
        $size_type = C('size_type');
        //取此身型原先有得数据
        $size_measure = D('size_measure')->where(array('order_item_id' => $order_item_id))->getField('data');
        $size_measure = unserialize($size_measure);
        //echo "<pre />";print_r($size_measure);exit;
       //处理需要的展示数据
        $size_data_arr = array();
        //身型绑定的数据
        $m_data = C('m_data');
        // 获取商品分类ID
        $cat_id=$product_info['catid'];
        if($cat_id==2170||$cat_id==2172){
            $m_data[22]=array(14);
        }else if($cat_id==2169){
            $m_data[22]=array(14);
        }else if($cat_id==2168){
            $m_data[22]=array(14);
        }else if($cat_id==2066){
            $m_data[22]=array(13);
        }
        //礼服特殊处理
        $product_model_id = $product_info['model_id'];
        if ($product_info['model_id'] == 23) {
            $cat_parentid = CategoryModel::get_category_parentid($product_info['catid']);
            if ($product_info['catid'] == 2061 || $cat_parentid == 2061) {
                $product_model_id = 233;
            } else {
                $product_model_id = 232;
            }
        }
        foreach ($size_type as $key => $val) {
            $typeid = $val['id'];
            if (!isset($size_measure[$typeid]) || !in_array($typeid, $m_data[$product_model_id])) continue;
            //区别九分裤 和 短裤
            /*
            if ($typeid == 3) { 
                if ($product_info['model_id'] == 18) {
                    $pants_cn_name = $orderfigure['attr_array']['148']['cn_attr_value_name'];
                } else if ($product_info['model_id'] == 2) {
                    $pants_cn_name = $orderfigure['attr_array']['147']['cn_attr_value_name'];
                } else if($product_info['model_id'] == 21){
                	$pants_cn_name = $orderfigure['attr_array']['137']['cn_attr_value_name'];
                }
                if (preg_match('/九分裤/', $pants_cn_name)) {
                    $val = $size_type[5];
                } else if (preg_match('/短裤/', $pants_cn_name)) {
                    $val = $size_type[6];
                }
                $typeid = $val['id'];
            }
            */
            //区别衬衫长袖短袖
            $isShirtLong = true;
            if ($typeid == 4) {
                //当选择的是短袖衬衫时
                if (isset($orderfigure['attr_array'][149]) && $orderfigure['attr_array'][149]['attr_value_id'] == 833) {
                    $isShirtLong = false;
                }
            }
            $size_data_arr[$typeid] = array();
            $size_data_arr[$typeid]['size_type_name'] = $isShirtLong ? $val['type_name'] : '短袖衬衫';
            $size_data_arr[$typeid]['model'] = $size_measure[$typeid]['model'];
            $size_data_arr[$typeid]['chima'] = $size_measure[$typeid]['chima'];
            //小脚裤特殊处理
            if ($size_data_arr[$typeid]['chima'] > 1000) {
                $size_data_arr[$typeid]['chima'] = strval($size_data_arr[$typeid]['chima'] - 1000) . "(小脚裤)";
            }
            //取尺码数据
            $size_name = D('size_name')
                ->field('id, size_name, more_type')
                ->where(array('more_type' => 0, 'size_type' => $val['id'], 'display' => 0))
                ->order('sort asc')
                ->select();

            foreach ($size_name as $k => $v) {
                //区别显示长短袖口袖长
                if ($typeid == 4) {
                    if ($isShirtLong) {
                        if (in_array($v['id'], array(29, 31))) {
                            unset($size_name[$k]);
                            continue;
                        }
                    } else {
                        if (in_array($v['id'], array(28, 30))) {
                            unset($size_name[$k]);
                            continue;
                        }
                    }
                }
                //区别显示长短袖口袖长
                $v['cysize'] = $size_measure[$typeid]['cy'][$v['id']];
                $v['mtmsize'] = $size_measure[$typeid]['mtm'][$v['id']];
                $size_name[$k] = $v;
            }
            $size_data_arr[$typeid]['size_name'] = $size_name;

            //取MTMADD数据
            if ($size_measure[$typeid]['mtmadd']) {
                $size_name_mtmadd = D('size_name')
                    ->field('id, size_name')
                    ->where(array('more_type' => 1, 'size_type' => $typeid, 'display' => 0))
                    ->order('sort asc')
                    ->select();
                foreach ($size_measure[$typeid]['mtmadd'] as $k => $v) {
                    $size_val = $v;
                    $size_data_arr[$typeid]['mtmadd'][$k] = array();
                    $size_data_arr[$typeid]['mtmadd'][$k]['size_val'] = $v;
                    foreach ($size_name_mtmadd as $kk => $vv) {
                        if ($k == $vv['id']) $size_data_arr[$typeid]['mtmadd'][$k]['size_name'] = $vv['size_name'];
                    }
                }
            }
            for ($i = count($size_measure[$typeid]['mtmadd']); $i < 3; $i++) {
                $size_data_arr[$typeid]['mtmadd'][$i] = array();;
            }

        }

        //条形码
        $Barcode = $orderfigure['order_id'] . 'M' . $order_item_id;
        $this->assign('Barcode', $Barcode);
        $this->assign('size_data_arr', $size_data_arr);
        //echo "<pre />";print_r($size_data_arr);exit;
        $this->assign('product', $product_info);
		foreach($orderfigure['attr_array'] as $ko=>&$vo){
			if(in_array($ko,array(57,72,114))){ 
				 if($product_info['show_thread_color']==2){
				 	$vo['cn_name']="插花眼和袖口最后一个扣眼";
				 }else{
					 $vo['cn_name']="所有的扣眼线";
				 }
			}
            if(in_array($ko,array(245,246,244,243,240,241,242))){
                if(isset($orderfigure['attr_array'][$ko]['cn_attr_value_name']) && $orderfigure['attr_array'][$ko]['cn_attr_value_name']){
                    $supplier_model = new SuppliersModel();
                    $supplier = $supplier_model->getSuppliersByName($orderfigure['attr_array'][$ko]['cn_attr_value_name']);
                    $orderfigure['attr_array'][$ko]['attr_value_id'] = $supplier['suppliers_id'];
                    $orderfigure['attr_array'][$ko]['lining_name'] = $supplier['lining_name'];
                    $orderfigure['attr_array'][$ko]['material'] = $supplier['material'];
                    $orderfigure['attr_array'][$ko]['breadth'] = $supplier['breadth'];
                }
            }
		}
		$orderfigure['eng_id'] = $product_info['eng_id'];
		$this->assign('orderfigure', $orderfigure);

        if ($product_info['model_id'] == 2) {
            $this->display('order_print_figure_god_n1');//两件套  OK
        } elseif ($product_info['model_id'] == 18) {
            $this->display('order_print_figure_threegod_n1');//三件套 OK
        } elseif ($product_info['model_id'] == 14) {
            $this->display('order_print_figure_shirt_n1');//衬衫  ok
		} elseif ($product_info['model_id'] == 30) {
            $this->display('order_print_figure_shirt_3d_n1');//3D衬衫
        } elseif ($product_info['model_id'] == 20) {  
            $this->display('order_vest_print_n1');     //马甲  OK
        } elseif ($product_info['model_id'] == 21) {  //西裤 OK
            $this->display('order_pants_print_n1');
		} elseif ($product_info['model_id'] == 32) {
            $this->display('order_pants_print_3d_n1');		//3D裤子2
        } elseif ($product_info['model_id'] == 1) {  //单西
            if($product_info['catid'] == 2162){
                $this->display('order_jacket_casual_custom_n1');  //休闲单西 ok
            }else{
                $this->display('order_jacket_custom_n1');  //ok
            }
		} elseif ($product_info['model_id'] == 31) { //3D单西
            $this->display('order_jacket_custom_3d_n1');   //2
        } elseif ($product_info['model_id'] == 22) {  //大衣  ok
            $this->display('order_coat_custom_n1');
        } elseif ($product_info['model_id'] == 23) {
            //特俗礼服处理
            $catid = $product_info['catid'];
            $parentid = D('category')
                ->where(array('id' => $catid))
                ->getField('parentid');
            if ($parentid > 0) $catid = $parentid;
			//echo $catid;exit;
            if ($catid == 2093) $this->display('order_full_dress_custom_n1');
            if ($catid == 2061) $this->display('order_three_full_dress_custom_n1');
        } elseif ($product_info['model_id'] == 25) {  //皮鞋 OK
            $this->display('order_shoes_custom_n1');
        }elseif ($product_info['model_id'] == 27) {//羊绒衫
            $this->display('order_sweater_custom');
        }elseif ($product_info['model_id'] == 26) {//牛仔裤  OK
            $this->display('order_jeans_custom');
        }elseif ($product_info['model_id'] == 36) {//其他产品  OK
            $this->display('order_other_product');
        }
        exit;
    }

    //软删除订单
    public function order_delete()
    {
        $oid = intval($_GET['oid']);
        $order_db = D('orders');
        $count = $order_db->where('id=' . $oid)->count();
        if (!$count) {
            $this->error('订单不存在！', U('order/order_list'));
        }
        $order_db->where('id=' . $oid)->save(array('order_status' => OrderModel::ORDER_DEL));

        $orderInfo = OrderModel::getOrderInfo($oid);
        //查询订单子数据
        $product = OrderModel::getOrderProductList($oid); //订单产品列表        
        //给配件商品增加库存
        foreach ($product as $key => $val) {

            $where_inventory = array(
                'order_item_id' => $val['id'],
                'change' => 0,
            );
            $inventory = D('inventory')->where($where_inventory)->select();

            foreach ($inventory as $kk => $vv) {
                //库存用料记录复原
                $addPost = array(
                    'type' => $vv['type'],
                    'tid' => $vv['tid'],
                    'order_sn' => $vv['order_sn'],
                    'order_id' => $vv['order_id'],
                    'order_item_id' => $vv['order_item_id'],
                    'pid' => $vv['pid'],
                    'amount' => $vv['amount'],
                    'remark' => '订单删除,恢复库存',
                );
                $res = SuppliersModel::inventoryAdd($addPost);
            }
        }
        $this->success('订单转移到已删除列表，您可以在那找到！', U('order/order_list'));
    }

    //编辑收货信息
    public function order_address_edit()
    {
        $order_id = intval($_GET['oid']);
        $orderInfo = OrderModel::getOrderInfo($order_id);
        if (!$orderInfo) {
            $this->error('订单不存在!', U('order/order_list'));
        }

        //if(in_array($orderInfo['order_status'], array(OrderModel::ORDER_COMPLETE, OrderModel::ORDER_CANCELED, OrderModel::ORDER_DEL)))
        //	{
        //		$this->error('订单已经完成，不能修改', U('order/order_list'));
        //	}

        //订单已经支付禁止修改
        /*if($orderInfo['payment_status'] == OrderModel::PAY_PAYED){
			$this->error('订单已经付款禁止修改!', U('order/order_edit', 'oid='.$order_id));
		}*/

        if ($_POST['dosubmit']) {
            if (empty($_POST['delivery_first_name']) && empty($_POST['delivery_last_name'])) {
                $this->error('请填写收货人姓名!', U('order/order_address_edit', 'oid=' . $order_id));
            }
			if (empty($_POST['delivery_address2']) && empty($_POST['delivery_address3'])) {
                $this->error('收货地址不完整!', U('order/order_address_edit', 'oid=' . $order_id));
            }
            if (!empty($_POST['delivery_cid'])) {
                $area_info = OrderModel::get_orderion_info($_POST['delivery_cid']);
                $_POST['delivery_country'] = $area_info['name'];
            }
            $order_db = D('orders');
            $order_db->create();
            $order_db->where('id=' . $order_id)->save();

            $this->success('编辑成功!', U('order/order_edit', 'oid=' . $order_id));
        } else {
            //国家列表
            $countryList = SiteModel::getCountryList();
            $this->assign('countryList', $countryList);

            $this->assign('order', $orderInfo);
            $this->display('order_address_edit');
        }
    }

    //修改订单产品
    public function order_product_edit()
    {
        $order_id = intval($_GET['oid']);
        $orderInfo = OrderModel::getOrderInfo($order_id);
        if (!$orderInfo) {
            $this->error('订单不存在!', U('order/order_list'));
        }

        if (in_array($orderInfo['order_status'], array(OrderModel::ORDER_COMPLETE, OrderModel::ORDER_CANCELED, OrderModel::ORDER_DEL))) {
            $this->error('订单已经完成，不能修改', U('order/order_list'));
        }

        //订单已经支付禁止修改
        /*if($orderInfo['payment_status'] == OrderModel::PAY_PAYED){
			$this->error('订单已经付款禁止修改!', U('order/order_edit', 'oid='.$order_id));
		}*/

        $product_db = D('product');

        //添加新产品
        if (isset($_POST['addsubmit'])) {
            $product_id = intval($_POST['product_id']);
            if (!$product_id) {
                $this->error('产品不存在!', U('order/order_product_edit', 'oid=' . $order_id));
            }
            //获取产品信息
            $where = array(
                'language_id' => $orderInfo['language_id'],
                'id' => $product_id,
            );
            $where['is_delete'] = 0;
            $product_db->field('id AS product_id,sn AS product_sn,sell_price,weight,stock,pri.name AS product_name');
            $product_db->join('product_items AS pri ON pri.product_id = product.id');
            $product = $product_db->where($where)->find();

            //获取产品属性列表
//			$attributeList = ProductModel::getProductRelationAttribteList($product_id, true);

            $goods_attr = '0';
            for ($i = 0; $i < $_POST['spec_count']; $i++) {
                if (is_array($_POST['spec_' . $i])) {
                    $temp_array = $_POST['spec_' . $i];
                    $temp_array_count = count($_POST['spec_' . $i]);
                    for ($j = 0; $j < $temp_array_count; $j++) {
                        if ($temp_array[$j] !== NULL) {
                            $goods_attr .= ',' . $temp_array[$j];
                        }
                    }
                } else {
                    if ($_POST['spec_' . $i] !== NULL) {
                        $goods_attr .= ',' . $_POST['spec_' . $i];
                    }
                }
            }

            $goods_attr = explode(',', $goods_attr);
            $k = array_search(0, $goods_attr);
            unset($goods_attr[$k]);


            //获取产品属性
            $product_attribute_db = D('product_attribute');
            $product_attribute = array();
            if ($goods_attr) {
                foreach ($goods_attr as $product_attr_id) {
                    $sql = "SELECT a.attr_name, g.attr_value, g.attr_price " .
                        "FROM product_attribute AS g, attribute  AS a " .
                        "WHERE g.attr_id = a.attr_id " .
                        "AND g.product_attr_id = '$product_attr_id' ";
                    $attributeList = $product_attribute_db->query($sql);
                    if ($attributeList) {
                        $attribute = reset($attributeList);
                        $product_attribute[$attribute['attr_name']] = $attribute['attr_value'];
                    }
                }
            }
            $product['attr'] = $product_attribute;

            //产品数量
            $qty = intval($_POST['number']);
            $qty = $qty ? ($qty > $product['stock'] ? $product['stock'] : $qty) : 1;

            $product['qty'] = $qty;

            //获取用户等级
            $rank_id = 0;
            if ($orderInfo['user_id']) {
                $userInfo = UserModel::getUserInfo($orderInfo['user_id']);
                $rank_id = $userInfo['rank_id'];
            }

            //获取产品最低价格
            $product['pay_price'] = ProductModel::getProductMinPrice($product_id, $qty, $rank_id);

            //添加订单关联产品
            OrderModel::insertOrderItems($order_id, $product);
            OrderModel::updateOrderPrices($order_id);
            $this->redirect(U('order/order_product_edit', 'oid=' . $order_id));
        } //编辑订单产品
        elseif (isset($_POST['dosubmit'])) {
            $oiids = $_POST['oiid'];
            $goods_prices = $_POST['goods_price'];
            $goods_numbers = $_POST['goods_number'];
            foreach ($oiids as $key => $oiid) {
                OrderModel::updateOrderItems($oiid, $goods_prices[$key], $goods_numbers[$key]);
            }
            OrderModel::updateOrderPrices($order_id);
            $this->success('编辑成功！', U('order/order_edit', 'oid=' . $order_id));
        } else {
            $productList = OrderModel::getOrderProductList($order_id); //订单产品列表
            $this->assign('productList', $productList);
            $this->assign('order', $orderInfo);
            $this->display('order_product_edit');
        }
    }

    //删除订单产品
    public function order_product_delete()
    {
        $order_id = intval($_GET['oid']);
        $orderInfo = OrderModel::getOrderInfo($order_id);
        if (!$orderInfo) {
            $this->error('订单不存在!', U('order/order_list'));
        }
        $order_items_db = D('orders_items');
        $count = $order_items_db->where('order_id=' . $order_id)->count();
        if ($count <= 1) {
            $this->error('订单最少要保留一件产品!', U('order/order_product_edit', 'oid=' . $order_id));
        }
        $oiid = intval($_GET['oiid']);
        $order_items_db->delete($oiid);
        OrderModel::updateOrderPrices($order_id);
        $this->redirect(U('order/order_product_edit', 'oid=' . $order_id));
    }

    //编辑订单时新增产品
    public function get_product_info_ajax()
    {
        $product_db = D('product');
        $where = array(
            'sn' => trim($_GET['sn']),
            'language_id' => intval($_GET['language_id']) ? intval($_GET['language_id']) : 1,
        );
        $where['is_delete'] = 0;
        $result = array(
            'error' => 0,
            'message' => null,
        );

        $product_db->field('id,sn,sell_price,stock,pri.name');
        $product_db->join('product_items AS pri ON pri.product_id = product.id');
        $product = $product_db->where($where)->find();
        if (!$product) {
            $result = array(
                'error' => 1,
                'message' => '产品不存在',
            );
        } else {
            //获取产品属性列表
            $attributeList = ProductModel::getProductRelationAttribteList($product['id'], true);
            $product['attr_list'] = $attributeList;
            $result['content'] = $product;
        }
        echo json_encode($result);
        exit;
    }

    //订单配置
    public function order_config()
    {
        $config = SiteModel::getShopConfigList();
        if (isset($_POST['dosubmit'])) {
            unset($_POST['dosubmit']);
            SiteModel::updateShopConfig($_POST);
            $this->success('保存成功', U('order/order_config'));
        } else {
            $this->assign('config', $config);
            $this->display('order_config');
        }
    }

    //订单退款列表
    public function pay_return_list()
    {
        $post = $_REQUEST;
        $where = array();
        $pay_return_db = D('orders_pay_return');

        $pageRows = 20;
        if (isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])) {
            $pageRows = intval($_REQUEST['pageRows']);
        }

        $order_sn = $_REQUEST['order_sn'];
        if ($order_sn) {
            $where['order_sn'] = $order_sn;
            $this->assign('order_sn', $order_sn);
        }

        $status = $_REQUEST['status'];
        if ($status) {
            $where['status'] = $status == 99 ? 0 : $status;
            $this->assign('status', $status);
        }

        $apply_type = $_REQUEST['apply_type'];
        if ($apply_type) {
            $where['apply_type'] = $apply_type == 99 ? 0 : $apply_type;
            $this->assign('apply_type', $apply_type);
        }

        //申请时间
        if ($post['add_start_time'] && $post['add_end_time']) {
            $start_time = strtotime($post['add_start_time']);
            $end_time = strtotime($post['add_end_time'] . ' 23:59:59');
            $where['add_time'] = array(array('egt', $start_time), array('lt', $end_time), 'and');
        } else {
            if ($post['add_start_time']) {
                $start_time = strtotime($post['add_start_time']);
                $where['add_time'] = array('egt', $start_time);
            }
            if ($post['add_end_time']) {
                $end_time = strtotime($post['add_end_time'] . ' 23:59:59');
                $where['add_time'] = array('lt', $end_time);
            }
        }
        $this->assign('add_start_time', $post['add_start_time']);
        $this->assign('add_end_time', $post['add_end_time']);
        //最后审核时间
        if ($post['end_start_time'] && $post['end_end_time']) {
            $start_time = strtotime($post['end_start_time']);
            $end_time = strtotime($post['end_end_time'] . ' 23:59:59');
            $where['end_time'] = array(array('egt', $start_time), array('lt', $end_time), 'and');
        } else {
            if ($post['end_start_time']) {
                $start_time = strtotime($post['end_start_time']);
                $where['end_time'] = array('egt', $start_time);
            }
            if ($post['end_end_time']) {
                $end_time = strtotime($post['end_end_time'] . ' 23:59:59');
                $where['end_time'] = array('lt', $end_time);
            }
        }
        $this->assign('end_start_time', $post['end_start_time']);
        $this->assign('end_end_time', $post['end_end_time']);

        //导出到EXCEL
        if ($post['doexcel'] == 1) {
            $returnList = $pay_return_db->where($where)->order('id DESC')->select();

            import('COM.XmlExcel');
            $excel = new XmlExcel;
            $excel_title = array('订单号', '收款人','申请类型', '申请金额', '退款金额', '状态', '申请人', '申请时间', '审核人', '审核时间');
            $excel->addHead($excel_title, '退款记录'); //设置CSV文件标题

            $excelList = array();
            foreach ($returnList as $key => $val) {
                $apply_type = $val['apply_type'] == 1 ? '重做' : '退款';
                if ($val['status'] == 3) {
                    $status = "已拒绝";
                } elseif ($val['status'] == 2) {
                    $status = $val['apply_type'] == 1 ? '重做完成' : '退款完成';
                } elseif ($val['status'] == 1) {
                    $status = "审核通过";
                } elseif ($val['status'] == 0) {
                    $status = "未处理";
                }
                $oneRes = array(
                    $val['order_sn'],
                    $val['user_name'],
                    $apply_type,
                    $val['apply_amount'],
                    $val['return_amount'],
                    $status,
                    $val['admin_user'],
                    date('Y-m-d H:i:s', $val['add_time']),
                    $val['check_user'],
                    date('Y-m-d H:i:s', $val['end_time']),
                );
                $excelList[] = $oneRes;
            }
            //echo '<pre />';
            //print_r($excelList);exit;
            $excel->addRows($excelList, '退款记录');

            $excel->export('退款列表' . date('Y-m-d His'));
            exit;
        }

        //分页
        $pay_return_db->where($where);
        $count = $pay_return_db->count();//总记录数
        import("ORG.Util.Page");// 导入分页类
        $Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
        $pageShow = $Page->show();// 分页显示输出
        $this->assign('pageShow', $pageShow);

        $returnList = $pay_return_db->limit($Page->firstRow . ',' . $Page->listRows)->where($where)->order('id DESC')->select();

        $this->assign('returnList', $returnList);
        $this->assign('pageRows', $pageRows);
        $this->display('pay_return_list');
    }

    //订单退款申请
    public function pay_return_apply()
    {
        //print_r($_SESSION);exit;
        $order_id = intval($_GET['oid']);
        $orderInfo = OrderModel::getOrderInfo($order_id);
        //申请类型 0 退款 1 重做
        $apply_type = intval($_REQUEST['apply_type']);

        if ($_POST['dosubmit']) {
            //保存数据
            $post = $_POST;
            $addData = array(
                'return_amount' => 0,
                'admin_note' => isset($post['admin_note']) ? trim($post['admin_note']) : NULL,
                'admin_user' => $_SESSION['admin_user_info']['user_name'],
                'status' => 0,
                'user_id' => isset($orderInfo['user_id']) ? intval($orderInfo['user_id']) : 0,
                'user_name' => $orderInfo['delivery_first_name'] . ' ' . $orderInfo['delivery_last_name'],
                'order_id' => $order_id,
                'order_sn' => $orderInfo['order_sn'],
                'apply_amount' => floatval($post['apply_amount']),
                'apply_type' => $apply_type,                
            );
            $paytid = OrderModel::updatePayReturnLogNew($addData);

            $comdata = array('paytid' => $paytid);
            //绑定图片
            $pay_return_photo_db = D('orders_pay_return_photo');
            $photo_name = $post['photo_name'];
            if ($photo_name) {
                $photo_name = explode(',', $photo_name);
                foreach ($photo_name as $key => $val) {
                    if (intval($val)) {
                        $pay_return_photo_db->where(array('fid' => $val))->save($comdata);
                    }
                }
            }
            $this->success('操作成功', U('order/pay_return_list'));
            exit;
        }

        $this->assign('apply_type', $apply_type);
        $this->assign('orderInfo', $orderInfo);
        $this->display('pay_return_apply');
    }

    //退款编辑
    public function pay_return_edit()
    {
        $pid = intval($_GET['pid']);
        $pay_return_db = D('orders_pay_return');
        $payInfo = $pay_return_db->find($pid);

        if (!$payInfo) {
            $this->error('非法操作', U('order/pay_return_list'));
        }
        if ($_POST['dosubmit']) {
            if ($payInfo['status'] == 2) {
                $this->error('已经完成禁止修改', U('order/pay_return_list'));
            }
            $total_amount = floatval($_POST['return_amount']);
            $data = array(
                'return_amount' => $total_amount,
                // 'return_points' => floatval($_POST['return_points']),
                // 'return_rank_points' => floatval($_POST['return_rank_points']),
                'refuse_note' => trim($_POST['refuse_note']),
                'check_user' => $_SESSION['admin_user_info']['user_name'],
                'status' => intval($_POST['status']),
            );
            if ($data['status'] == 2) $data['return_amount'] = $payInfo['return_amount'];

            if (OrderModel::updatePayReturnLogNew($data, $pid)) {
                //完成
                if ($data['status'] == 2) {
                    //退款退积分
                    UserModel::logAccountChange($payInfo['user_id'], $total_amount, 0, (-1) * $data['return_points'], $data['return_rank_points'], L('_ORDER_REFUND_') . ' ' . L('order number : ') . $payInfo['order_sn'], UserModel::ACT_REFUND);
                    $order_id = OrderModel::getOrderId($payInfo['order_sn']);
                    $orderInfo = OrderModel::getOrderInfo($order_id);

                    if ($orderInfo['pay_integral']) {
                        //退还赠送积分
                        UserModel::logAccountChange($payInfo['user_id'], 0, 0, 0, (-1) * $orderInfo['pay_integral'], L('gift_points') . ' ' . L('order number : ') . $payInfo['order_sn'], UserModel::ACT_REFUND);
                    }


                    //退款邮件
                    if ($orderInfo['delivery_email'] && $total_amount > 0 && $total_amount > '0.00') {
                        $email_template = UserModel::getEmailTemplateInfo('payReturnEmail', $orderInfo['language_id']);
                        //发邮件
                        if ($email_template) {
                            $mailInstance = D(WEB_APP_NAME . '://Email');
                            $content = str_replace('{$user_name}', $orderInfo['delivery_first_name'] . ' ' . $orderInfo['delivery_last_name'], $email_template['content']);
                            $content = str_replace('{$admin_note}', $data['admin_note'], $content);
                            $content = str_replace('{$order_sn}', $orderInfo['order_sn'], $content);
                            $title = str_replace('{$order_sn}', $orderInfo['order_sn'], $email_template['title']);
                            $content = $mailInstance->replaceMail($content);
                            $title = $mailInstance->replaceMail($title);
                            $mailInstance->sendMail($orderInfo['delivery_email'], $title, $content);
                        }
                    }
                }


                $this->success('操作成功', U('order/pay_return_list'));
            } else {
                $this->error('操作失败', U('order/pay_return_list'));
            }
        } else {

            $orderInfo = OrderModel::getOrderInfo($payInfo['order_id']);
            $orderInfo['product'] = OrderModel::getOrderProductList($orderInfo['id']); //订单产品列表
            $this->assign('order', $orderInfo);

            if ($orderInfo['coupon_code']) {
                $coupon_info = M('favorable')->field('status,coupon_money,type')->where("coupon_code='" . $orderInfo['coupon_code'] . "'")->find();
                if ($coupon_info['status'] == 4 || $coupon_info['type'] == 4) {//折扣优惠码
                    $this->assign('coupon_info', $coupon_info);
                }
            }

            //会员信息
            $userInfo = UserModel::getUserInfo($orderInfo['user_id']);
            $this->assign('user', $userInfo);

            //查询图片
            $pay_return_photo_db = D('orders_pay_return_photo');
            $pay_return_photo = $pay_return_photo_db->where(array('paytid' => $payInfo['id']))->order('fid asc')->select();
            $this->assign('comment_photo', $pay_return_photo);

            //查询操作人记录
            $pay_return_log_db = D('orders_pay_return_log');
            $pay_return_log = $pay_return_log_db->where(array('paytid' => $payInfo['id']))->order('id desc')->select();
            $this->assign('pay_return_log', $pay_return_log);

            $this->assign('pay', $payInfo);
            $this->display('pay_return_edit');
        }
    }

    //进货单
    public function purchased_list()
    {
        if ($_POST['dosubmit']) {
            $ordersn = $_POST['ordersn'];
            if (empty($ordersn)) {
                $this->redirect('order/purchased_list');
            }
//			$ordersn = explode(PHP_EOL, $ordersn);
            $ordersn = explode("\n", str_replace("\r", '', $ordersn));
//			$ordersn = array('201103180005','201303270001','201304100001','201304110001','201304110002');
//			$ordersn = array('201304110001');
            $isspec = intval($_POST['isspec']);
            $order_db = D('orders');
            $orderList = array();
            foreach ($ordersn as $order_sn) {
                if (empty($order_sn)) continue;
                $orderInfo = OrderModel::getPurchasedProductList($order_sn, $isspec);

                if ($orderInfo) {
                    $orderList[] = $orderInfo;
                }
            }
            if (empty($orderList)) {
                $this->redirect('order/purchased_list', null, 3, '搜索订单不在');
            }
            $this->assign('orderList', $orderList);
            $this->display('purchased_print');
        } else {
            $this->display('purchased_list');
        }
    }

    //扫描订单
    public function screenBarcode()
    {
        unset($_SESSION['barcodeList']);

        if ($_POST['addaction']) {
            $this->assign('jumpUrl', U('order/screenBarcode'));
            unset($_SESSION['barcodeList']);

            $order_sn = trim($_POST['order_sn']);
            $order_id = OrderModel::getOrderId($order_sn);
            if (!$order_id) {
                $this->error('订单不存在,订单号：' . $order_sn);
            }

            $orderInfo = OrderModel::getOrderInfo($order_id);
            if ($orderInfo['order_status'] != OrderModel::ORDER_CONFIRMED) {
                $this->error('订单未确认、已经完成或者取消，不能发货！订单号：' . $order_sn);
            } elseif ($orderInfo['payment_status'] != OrderModel::PAY_PAYED) {
                $this->error('订单非支付状态，不能发货！订单号：' . $order_sn);
            }
            if (!isset($_POST['send']) || empty($_POST['send'])) {
                $this->error('没有扫描商品，订单号：' . $order_sn);
            }
            $shipping_no = trim($_POST['shipping_no']);
            if (empty($shipping_no)) {
                $this->error('没有扫描快递号，订单号：' . $order_sn);
            }
            $post = $_POST['send'];
            foreach ($post as $key => $send) {
                if (empty($send['id']) || $send['number'] == 0) {
                    unset($post[$key]);
                }
            }
            if (empty($post)) {
                $this->error('未扫描商品，订单号：' . $order_sn);
            }

            $productList = OrderModel::getOrderDeliveryProductList($order_id);
            if (!$productList) {
                $this->error('订单无商品，订单号：' . $order_sn);
            }

            $order_delivery_db = D('orders_delivery');
            $order_delivery_product_db = D('orders_delivery_product');

            //入库发货单
            $data = array(
                'delivery_sn' => OrderModel::getDeliverySn(),
                'order_id' => $order_id,
                'add_time' => time(),
                'action_user' => $_SESSION['admin_user_info']['user_name'],
                'shipping_no' => $shipping_no,
                'status' => 2,
                'update_time' => time(),
            );
            $delivery_id = $order_delivery_db->add($data);

            foreach ($productList as $item) {
                //商品要发货
                $send_number = intval($post[$item['id']]['number']);
                if (isset($post[$item['id']]['id']) && $send_number && $item['stock']) {
                    //如果填写的发货数大于要发货的数量
                    if ($send_number > ($item['qty'] - $item['send_number'])) {
                        $send_number = $item['qty'] - $item['send_number'];
                    }
                    //如果大于库存
                    if ($send_number > $item['stock']) {
                        $send_number = $item['stock'];
                    }

                    //发货单商品
                    if ($delivery_id) {
                        $pro_data = array(
                            'orders_delivery_id' => $delivery_id,
                            'orders_items_id' => $item['id'],
                            'send_number' => $send_number,
                        );
                        $order_delivery_product_db->add($pro_data);
                    }
                }
            }

            //更改发货状态
            OrderModel::updateDeliveryStatus($order_id);

            $orderInfo = OrderModel::getOrderInfo($order_id);
            $deliveryInfo = OrderModel::getDeliveryInfo($delivery_id);

            /*此发货单邮件*/
            $orderInfo['delivery_sn'] = $deliveryInfo['delivery_sn'];
            $orderInfo['shipping_no'] = $deliveryInfo['shipping_no'];
            $orderInfo['shipping_time'] = $deliveryInfo['update_time'] ? $deliveryInfo['update_time'] : $deliveryInfo['add_time'];

            $orderInfo['deliveryList'] = OrderModel::getDeliveryProductList($order_id, $delivery_id);

            //发货邮件
            $orderInfo['productList'] = OrderModel::getDeliveryProductList($order_id, $delivery_id); //订单产品列表
            $email_template = UserModel::getEmailTemplateInfo('orderSendEmail', $orderInfo['language_id']);
            if ($email_template) {
                $mailInstance = D(WEB_APP_NAME . '://Email');
                $content = $email_template['content'];
                $order_status_url = '';
                if ($orderInfo['user_id']) {
                    $order_status_url = 'http://' . $_SERVER['HTTP_HOST'] . '/order/order_edit_status/oid/' . $orderInfo['id'] . '/status/2';
                }
                $content = str_replace('{$order_status_url}', $order_status_url, $content);
                $content = $mailInstance->replaceMail($content, $orderInfo);
                $title = $mailInstance->replaceMail($email_template['title']);
                $mailInstance->sendMail($orderInfo['delivery_email'], $title, $content);
            }

            //添加订单日志
            $logData = array(
                'order_id' => $orderInfo['id'],
                'order_status' => $orderInfo['order_status'],
                'payment_status' => $orderInfo['payment_status'],
                'shipping_status' => $orderInfo['shipping_status'],
                'action_notice' => $_POST['action_notice'] ? trim($_POST['action_notice']) : '已发货',
            );
            OrderModel::insertOrdersLog($logData);

            $this->success('操作成功', U('order/screenBarcode'));

        } else {
            $this->display('screen_barcode');
        }
    }

    //获取扫描订单中的商品
    public function getsceenproduct_ajax()
    {
        $result = array(
            'error' => 1,
            'message' => null,
        );
        $order_sn = trim($_REQUEST['order_sn']);
        $order_id = OrderModel::getOrderId($order_sn);
        if (!$order_id) {
            $result['message'] = '订单号不存在，订单号：' . $order_sn;
            echo json_encode($result);
            exit;
        }

        $barcode = trim($_REQUEST['barcode']);

        /*if(!isset($_SESSION['barcodeList']['order_id'])){
			$_SESSION['barcodeList']['order_id'] = $order_id;
		}*/

        /*if($_SESSION['barcodeList']['order_id'] != $order_id){
			$result = array(
				'error' => 2,
				'message' => '请不要一次扫描多个订单号',
			);
			echo json_encode($result);exit;
		}*/


        //物流号
        $sn_pre = C('product_sn_pre') ? C('product_sn_pre') : 'SN';
        if ($barcode && $barcode != $order_sn && substr($barcode, 0, 2) != $sn_pre) {
            $result = array(
                'error' => 0,
                'shipping_no' => $barcode
            );
            echo json_encode($result);
            exit;
        }

//		$barcode =$order_sn;
        if (strlen($barcode) < 9) {
            $result['message'] = '非法条形码，订单号：' . $barcode;
            echo json_encode($result);
            exit;
        }
        $order_items_id = substr($barcode, 8);
//		$order_items_id = 34;

        $orderInfo = OrderModel::getOrderInfo($order_id);

        $order_delivery_db = D('orders_delivery');
        $order_delivery_db->field('status');
        $deliveryInfo = $order_delivery_db->where('order_id=' . $order_id . '')->find();

        if ($orderInfo['order_status'] != OrderModel::ORDER_CONFIRMED) {
            $result['message'] = '订单未确认、已经完成或者取消，不能发货！订单号：' . $barcode;
        } elseif ($orderInfo['payment_status'] != OrderModel::PAY_PAYED) {
            $result['message'] = '订单非支付状态，不能发货！订单号：' . $barcode;
        } elseif ($deliveryInfo['status'] == 1) {
            $result['message'] = '发货单已存在，状态未发货！订单号：' . $barcode;
        } elseif ($deliveryInfo['status'] == 2) {
            $result['message'] = '发货单已存在，状态已发货！订单号：' . $barcode;
        } else {
            $html = '';
            $productList = OrderModel::getOrderDeliveryProductList($order_id);
            if (!$productList) {
                $result['message'] = '订单无商品，订单号：' . $barcode;
            } else {
                foreach ($productList as $product) {
                    //if($product['qty'] == $product['send_number'])continue;
                    if ($product['id'] == $order_items_id) {
                        $total = $product['qty'] - $product['send_number'];
                        if ($_SESSION['barcodeList'][$order_items_id] > $total) {
                            $result = array(
                                'error' => 2,
                                'message' => '扫描商品数量多于要发货的数量，订单号：' . $barcode,
                            );
                            echo json_encode($result);
                            exit;
                        }
                        if (isset($_SESSION['barcodeList'][$order_items_id])) {
                            $barnumber = $_SESSION['barcodeList'][$order_items_id] + 1;
                        } else {
                            $barnumber = 1;
                        }
                        $_SESSION['barcodeList'][$order_items_id] = $total;
                        $result['add'] = array(
                            'id' => $product['id'],
                            'num' => $total,
                            'total' => $total,
                        );
//					}elseif(substr($barcode, 0,2) == $sn_pre){
//						$result = array(
//								'error' => 2,
//								'message' => '扫描商品不存在订单中',
//							);
//							echo json_encode($result);exit;
                    }
                    //第一次扫描，扫描输入为订单号时
                    if ($order_sn == $barcode) {
                        $html .= '<tr id="trid-' . $product['id'] . '">';
                        $html .= '<td align="center"><img src="' . $product['small_img'] . '" width="100" height="100" /></td>';
                        $html .= '<td align="center">' . $product['product_sn'] . '</td>';
                        $html .= '<td>' . $product['product_name'] . '<br/>';
                        $html .= $product['attr'];
                        $html .= '</td>';
                        $html .= '<td align="center">' . $product['cost_price'] . '</td>';
                        $html .= '<td align="center">' . $product['qty'] . '</td>';
                        $html .= '<td align="center">' . $product['send_number'] . '</td>';
                        $html .= '<td align="center">';
                        $html .= '<input type="hidden" value="' . $product['id'] . '" name="send[' . $product['id'] . '][id]" />';
                        $html .= '<input type="text" id="number-' . $product['id'] . '" size="4" value="' . ($product['qty'] - $product['send_number']) . '" onblur="javascript:checknumber(this.value,' . ($product['qty'] - $product['send_number']) . ')" name="send[' . $product['id'] . '][number]" autocomplete="off">';
                        $html .= '</tr>';
                        $i++;
                    }

                }

                $result['error'] = 0;
                $result['content'] = $html;

            }
        }

//		echo str_replace("\\","", json_encode($result));
        echo json_encode($result);
    }


    /**
     * 获取扫描商品列表
     */
    public function get_screen_barcode_product_ajax()
    {
        $result = array(
            'error' => 1,
            'message' => null,
        );
        $order_sn = trim($_GET['order_sn']);
        $order_id = OrderModel::getOrderId($order_sn);


        if (!$order_id) {
            $result['message'] = '订单号不存在，订单号：' . $order_sn;
        } else {
            $orderInfo = OrderModel::getOrderInfo($order_id);
            if ($orderInfo['order_status'] != OrderModel::ORDER_CONFIRMED) {
                $result['message'] = '订单未确认、已经完成或者取消，不能发货！';
            } elseif ($orderInfo['payment_status'] != OrderModel::PAY_PAYED) {
                $result['message'] = '订单非支付状态，不能发货！';
            } else {
                $html = '';
                $productList = OrderModel::getOrderDeliveryProductList($order_id);
                if (!$productList) {
                    $result['message'] = '订单无商品，订单号：' . $order_sn;
                } else {
                    foreach ($productList as $product) {
                        if ($product['qty'] == $product['send_number']) continue;

                        $html .= '<tr id="' . $product['product_sn'] . '-' . $product['id'] . '">';
                        $html .= '<td align="center"><img src="' . $product['small_img'] . '" /></td>';
                        $html .= '<td align="center">' . $product['product_sn'] . '</td>';
                        $html .= '<td>' . $product['product_name'] . '<br/>';
                        $html .= $product['attr'];
                        $html .= '</td>';
                        $html .= '<td align="center">' . $product['cost_price'] . '</td>';
                        $html .= '<td align="center">' . $product['qty'] . '</td>';
                        $html .= '<td align="center">' . $product['send_number'] . '</td>';
                        $html .= '<td align="center">';
                        $html .= '<input type="hidden" value="' . $product['id'] . '" name="send[' . $product['id'] . '][id]" />';
                        $html .= '<input type="text" size="4" value="0" onblur="javascript:checknumber(this.value,' . ($product['qty'] - $product['send_number']) . ')" name="send[' . $product['id'] . '][number]" autocomplete="off">';
                        $html .= '</tr>';
                    }
                    $result = array(
                        'error' => 0,
                        'content' => $html,
                    );
                }
            }
        }
        echo json_encode($result);
    }

    //修改优惠金额
    public function change_discount_amount_ajax()
    {
        $result = array(
            'error' => 1,
            'message' => null,
        );
        $discount_amount = floatval($_GET['discount_amount']);
        $order_id = intval($_GET['oid']);
        $orderInfo = OrderModel::getOrderInfo($order_id);
        //判断下单用户是否是合作伙伴
        $is_parnter=D('users')->where(array('id'=>$orderInfo['user_id']))->getField("is_partner");
        if (!$orderInfo) {
            $result['message'] = '订单不存在！';
        } else {
            $pay_amount = $orderInfo['pay_amount'];
            if ($orderInfo['discount_amount'] > 0) {
                $result = array(
                    'error' => 0,
                    'amount' => $pay_amount,
                );
            } else {
                if ($pay_amount <= $discount_amount) {
                    $data['payment_status'] = OrderModel::PAY_PAYED;
                    $newamount = '0.00';
                } else {
                    $newamount = floatval($pay_amount - $discount_amount);
                }
                $data['pay_amount'] = $newamount;
                $data['discount_amount'] = $discount_amount;
                $order_db = D('orders');
                $order_db->where('id=' . $order_id)->save($data);
                $result = array(
                    'error' => 0,
                    'amount' => $newamount,
                );
            }
            if($is_parnter){
                //订单商品
                $order_p=D('orders_items')->where('order_id = '.$order_id)->select();
                $product_name_str ="";
                foreach($order_p as $k=>$v)
                {
                    if($k==0){
                        $product_name_str .= $v['product_name']."x".$v['qty'];
                    }else {
                        $product_name_str .= ",".$v['product_name']."x".$v['qty'];
                    }
                }
                 //给用户发送下单通知短信
                  $address=$orderInfo['delivery_province'].$orderInfo['delivery_city'].$orderInfo['delivery_address'].$orderInfo['delivery_address2'];
                  $ShortMessage=A("ShortMessage");
                 $str_short_message='{"product_str":"'. $product_name_str.'","pay_money":"'.$orderInfo['pay_amount'].'","address":"'.$address.'","order_sn":"'.$orderInfo['order_sn'].'","days":"10-25"}';
                 //$short_mesg_result=$ShortMessage->send_message('SMS_4910029',$orderInfo['delivery_phone'],$str_short_message);
                // if($short_mesg_result){
                   // Log::write('合作伙伴下单短信，订单号'.$orderInfo['order_sn'].'，时间：'.date("Y-m-d H:i:s",time()));
                // }
            }
        }
        echo json_encode($result);
    }

    //订单批量下载
    public function order_beach_download()
    {
        if ($_POST['dosubmit']) {
            $ordersn = $_POST['ordersn'];
            if (empty($ordersn)) {
                $this->redirect('order/purchased_list');
            }

            $ordersn = explode("\n", str_replace("\r", '', $ordersn));
//		$ordersn = explode(PHP_EOL, $ordersn);		


//			$ordersn = array('201103180005','201303270001','201304100001','201304110001','201304110002');
//			$ordersn = array('201304110001');
            $order_db = D('orders');
            $orderList = array();

            $order_print_dir = TEMP_PATH . 'orderprint/' . date('Y-m-d') . '/';
            mkdirs($order_print_dir);
            import('COM.File');
            $fileList = array();
            $orderSn = '';
            foreach ($ordersn as $order_sn) {
                if (empty($order_sn)) continue;
                if ($$orderSn == '')
                    $orderSn = $order_sn;
                else
                    $orderSn .= ',' . $order_sn;
                $order_id = OrderModel::getOrderId($order_sn);
                $orderInfo = OrderModel::getOrderInfo($order_id);
                $orderInfo['productList'] = OrderModel::getOrderProductList($order_id); //订单产品列表
                $orderInfo['shipping_no'] = OrderModel::getShippingNumber($order_id);
                if ($orderInfo) {
                    $this->assign('orderInfo', $orderInfo);

                    if ($orderInfo['user_id']) {
                        $user_info = UserModel::getUserInfo($orderInfo['user_id']);
                        $len = strlen($user_info['username']);
                        if ($len > 6)
                            $str = substr($user_info['username'], 0, 6);
                        else
                            $str = $user_info['username'];

                        $this->assign('user_name', $user_info['username']);
                    } else {
                        $len = strlen($orderInfo['delivery_first_name']);
                        if ($len >= 6) {
                            $str = substr($orderInfo['delivery_first_name'], 0, 6);
                        } else {
                            $len = 6 - $len;
                            $str1 = substr($orderInfo['delivery_last_name'], 0, $len);
                            $str = $orderInfo['delivery_first_name'] . $str1;
                        }
                    }

                    $content = $this->fetch('order_beach_download_tpl');
                    $filename = ($orderInfo['stockout'] ? '' . $str . '-Y' : '' . $str . '-N') . '-' . $orderInfo['order_sn'] . '.html';
                    //echo $order_print_dir.$filename;exit;
                    $fileClass = new File($order_print_dir . $filename, 'w');
                    $fileClass->write($content);
                    $fileClass->save();
                    $fileList[] = $order_print_dir . $filename;
                }
            }

            if (empty($fileList)) {
                $this->redirect('order/order_beach_download', null, 3, '搜索订单不在');
            }
            $zip = new ZipArchive();
            $zipname = $order_print_dir . date('Y-m-d') . '-save-local';
            if (!file_exists($zipname)) {
                $zip->open($zipname . '.zip', ZipArchive::OVERWRITE);//创建一个空的zip文件
                foreach ($fileList as $file) {
                    $zip->addFile($file);
                }
                $zip->close();
            }
            import('ORG.Net.Http');
            Http::download($zipname . '.zip');
            $fileClass->clearDir($order_print_dir);
        }
        $this->display('order_beach_download');
    }

    //批量打印快递单
    public function order_export_express()
    {
        $productList = OrderModel::getOrderTempProductList();
        if (isset($_POST['dosubmit'])) {

            $where = array(
                'order_status' => OrderModel::ORDER_CONFIRMED,
                'shipping_status' => array('in', '0,3'),
            );

            //查单方式
            $export_type = intval($_POST['export_type']);
            //按配送方式
            if ($export_type == 1) {
                $where['order_sn'] = array('in', implode(',', explode("\n", str_replace("\r", '', $_POST['ordersn']))));
            } else {
                $shipping_id = intval($_POST['shipping_id']);
                $where['shipping_id'] = $shipping_id;
                if (isset($_POST['start_time']) && $_POST['start_time'] && isset($_POST['end_time']) && $_POST['end_time']) {
                    $where['start_time'] = array(array('gt', strtotime(trim($_POST['start_time']))), array('lt', strtotime(trim($_POST['end_time']) . ' 23:59:59')), 'AND');
                }
            }

            $order_db = D('orders');

            $orderList = $order_db->field('order_sn,delivery_first_name,delivery_last_name,delivery_email,delivery_phone,delivery_country,delivery_province,delivery_city,delivery_address,delivery_address2,delivery_address3,delivery_postcode')->where($where)->select();
//		echo $order_db->getLastSql();exit;
            if (empty($orderList)) {
                $this->redirect('order/order_export_express', null, 3, '搜索订单不在');
            }

            $goods_array = array();
            $goods_data = explode(',', $_POST['goods_data']);
            foreach ($goods_data as $goods_id) {
                $proinfo = $productList[$goods_id];
                $goods_array[] = $proinfo['name'] . ' ' . $proinfo['name_en'] . ' ' . $proinfo['price'];
            }

            $shippingInfo = ShippingModel::getShippingInfo($shipping_id);
            $excel_name = $shippingInfo['name'] . '-' . date('Y-m-d');

            import('COM.XmlExcel');
            $xls = new XmlExcel;
            $excel_title = array('订单号', '收件人姓名', '收件人城市', '收件人省市', '收件人国家', '收件人地址', '收件人地址2', '收件人地址3', '邮政编码', '收件人电话', '邮寄商品1', '邮寄商品2', '邮寄商品3');
            $xls->addHead($excel_title); //设置CSV文件标题

            foreach ($orderList as $order) {
                $data = array(
                    $order['order_sn'],
                    $order['delivery_first_name'] . ' ' . $order['delivery_last_name'],
                    $order['delivery_city'],
                    $order['delivery_province'],
                    $order['delivery_country'],
                    $order['delivery_address'],
                    $order['delivery_address2'],
                    $order['delivery_address3'],
                    $order['delivery_postcode'],
                    $order['delivery_phone'],
                    $goods_array[0],
                    isset($goods_array[1]) ? $goods_array[1] : ' ',
                    isset($goods_array[2]) ? $goods_array[2] : ' '
                );
                $xls->addRow($data);
            }
            $xls->export($excel_name);
        } else {
            $shippingList = ShippingModel::getShippingList();
            $this->assign('shippingList', $shippingList);
            $this->assign('productList', $productList);
            $this->display('order_export_express');
        }
    }

    public function order_express_product_list()
    {
        $productList = OrderModel::getOrderTempProductList();
        $this->assign('productList', $productList);
        $this->display('order_express_product_list');
    }

    //编辑快递单商品
    public function order_express_product_edit()
    {
        $oid = intval($_GET['oid']);
        $express_temp_product = D('express_temp_product');
        if (isset($_POST['dosubmit'])) {
            $express_temp_product->create();
            if ($oid) {
                $express_temp_product->where('id=' . $oid)->save();
            } else {
                $express_temp_product->add();
            }
            $this->success('操作成功', U('order/order_express_product_list'));
        } else {
            if ($oid) {
                $product = $express_temp_product->find($oid);
            }
            $this->assign('product', isset($product) ? $product : null);
            $this->display('order_express_product_edit');
        }
    }

    //删除快递单商品
    public function order_express_product_del()
    {
        $oid = intval($_GET['oid']);
        $express_temp_product = D('express_temp_product');
        $express_temp_product->delete($oid);
        $this->success('操作成功', U('order/order_express_product_list'));
    }

    /**
     * 退换货列表
     */
    public function order_purchase_list()
    {
        $where = array(
            'parent_id' => 0,
        );

        $pageRows = 20;
        if (isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])) {
            $pageRows = intval($_REQUEST['pageRows']);
        }

        $order_purchase_db = D('orders_purchase');
        //分页
        $order_purchase_db->where($where);
        $count = $order_purchase_db->count();//总记录数
        import("ORG.Util.Page");// 导入分页类
        $Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
        $pageShow = $Page->show();// 分页显示输出
        $this->assign('pageShow', $pageShow);

        $order_purchase_db->field('id,order_sn,product_name,status,add_time,purchase_type,contact_name');
        $order_purchase_db->limit($Page->firstRow . ',' . $Page->listRows);
        $order_purchase_db->where($where)->order('id DESC');
        $purchaseList = $order_purchase_db->select();

        $this->assign('purchaseList', $purchaseList);
        $this->display('order_purchase_list');

    }

    //查看退换货记录
    public function order_purchase_edit()
    {
        $orders_purchase_db = D('orders_purchase');
        $pur_id = intval($_GET['pur_id']);
        $purchaseInfo = $orders_purchase_db->find($pur_id);
        if (!$purchaseInfo) {
            $this->error('记录不存在！', url('user/order_purchase_list'));
        }

        if ($_POST['dosubmit']) {

            $data = array(
                'parent_id' => $pur_id,
                'description' => trim($_POST['description']),
                'add_time' => time(),
            );
            $purid = $orders_purchase_db->add($data);
            $orders_purchase_db->where('id=' . $pur_id)->save(array('status' => 2));
            if ($purid) {
                //退换货回复邮件
                if ($purchaseInfo['contact_email']) {
                    $language_id = D('users')->where('id=' . $purchaseInfo['user_id'])->getField('language_id');
                    $email_template = UserModel::getEmailTemplateInfo('purchaseEmail', $language_id);

                    //发邮件
                    if ($email_template) {
                        $mailInstance = D(WEB_APP_NAME . '://Email');
                        $content = str_replace('{$user_name}', $purchaseInfo['contact_name'], $email_template['content']);
                        $content = str_replace('{$purchase_content}', trim($_POST['description']), $content);
                        $title = str_replace('{$order_sn}', $purchaseInfo['order_sn'], $email_template['title']);
                        $content = $mailInstance->replaceMail($content);
                        $title = $mailInstance->replaceMail($title);
                        $mailInstance->sendMail($purchaseInfo['contact_email'], $title, $content);
                    }
                }
                $this->success('回复成功', U('order/order_purchase_list'));
            } else {
                $this->error('回复失败', U('order/order_purchase_list'));
            }
        } else {
            $photoList = array();
            if ($purchaseInfo['images']) {
                $photoList = explode(',', $purchaseInfo['images']);
                foreach ($photoList as $key => $img) {
                    if (empty($img)) unset($photoList[$key]);
                }
            }
            $orders_purchase_db = D('orders_purchase');
            $mesgList = $orders_purchase_db->where('parent_id=' . $pur_id)->order('id DESC')->select();
            $this->assign('mesgList', $mesgList);
            $this->assign('photoList', $photoList);
            $this->assign('purchaseInfo', $purchaseInfo);
            $this->display('order_purchase_edit');
        }
    }

    //导出订单邮箱
    public function order_email_export()
    {
        import('COM.XmlExcel');
        $excel = new XmlExcel;
        $excel_title = array('email');
        $excel->addHead($excel_title); //设置CSV文件标题

        $order_db = D('orders');
        $emailList = $order_db->field('delivery_email')->select();
        $excel->addRows($emailList);
        $excel->export('order_email');
    }

    //导出订单列表
    public function order_list_export()
    {

        $post = $_REQUEST;

//		//发货列表
//		if(isset($_GET['order_status']) && intval($_GET['order_status'])==1 && isset($_GET['payment_status']) && intval($_GET['payment_status'])==1 && isset($_GET['shipping_status']) && intval($_GET['shipping_status'])==0 ){
//			$_POST['search'] = 1;
//			$_POST['order_status'] = 1;
//			$_POST['payment_status'] = 1;
//			$_POST['shipping_status'] = 0;
//		}

        //根据buttonselect作判断
        $buttonselect = $post['buttonselect'];
        if ($buttonselect == 'wait') {
            $post['order_status'] = 1;
            $post['payment_status'] = 1;
            $post['start_time'] = date('Y-m-d H:i:s', time() - 3600 * 24);
        } else if ($buttonselect == 'ok') {
            $post['order_status'] = 1;
            $post['payment_status'] = 1;
            $post['end_time'] = date('Y-m-d H:i:s', time() - 3600 * 24);
        } else if ($buttonselect == 'pause') {
            $post['order_status'] = -3;
        } else {
            $buttonselect = "all";
        }
        $this->assign('buttonselect', $buttonselect);
        // var_dump($post);die;
        $where = array();
        //合作伙伴专用
        if ($_REQUEST['address_id']) {
            $where['address_id'] = $_REQUEST['address_id'];
        }

        //搜索订单状态
        $order_status = 9999;
        if (isset($post['order_status']) && $post['order_status'] != 9999) {
            $where['orders.order_status'] = $post['order_status'];
            $order_status = $post['order_status'];
        }
        $this->assign('order_status', $order_status);
        //搜索支付状态
        $payment_status = 9999;
        if (isset($post['payment_status']) && $post['payment_status'] != 9999) {
            $where['orders.payment_status'] = $post['payment_status'];
            $payment_status = $post['payment_status'];
        }
        $this->assign('payment_status', $payment_status);
        //搜索配送状态
        $shipping_status = 9999;
        if (isset($post['shipping_status']) && $post['shipping_status'] != 9999) {
            $where['orders.shipping_status'] = $post['shipping_status'];
            $shipping_status = $post['shipping_status'];
        }
        $this->assign('shipping_status', $shipping_status);
        //搜索关键词
        if (isset($post['keyword']) && $post['keyword']) {
            $post['keyword'] = trim($post['keyword']);
            if ($post['searchtype'] == 0) {
                $where['orders.order_sn'] = array('like', '%' . $post['keyword'] . '%');
            } else if ($post['searchtype'] == 1) {
                //$where['orders.delivery_last_name'] = array('like', '%'.$post['keyword'].'%');
                $where[] = "orders.delivery_last_name LIKE '%{$post['keyword']}%' OR orders.delivery_first_name LIKE  '%{$post['keyword']}%'";
            } else if ($post['searchtype'] == 2) {
                $where['orders.payment_time'] = array('like', '%' . strtotime($post['keyword']) . '%');
            } else if ($post['searchtype'] == 3) {
                $where['orders.id'] = $post['keyword'];
            } else if ($post['searchtype'] == 4) {
                $user_id = M('users')->where(array('email' => $post['keyword']))->getField('id');
                $where['orders.user_id'] = $user_id > 0 ? $user_id : '-999';
            }
            $this->assign('keyword', $post['keyword']);
        }
        $this->assign('searchtype', $post['searchtype']);
        //付款时间查询
        $orders = D('orders');
        //if(isset($post['time_search'])){ 
        if ($post['start_time'] && $post['end_time']) {
            $start_time = strtotime($post['start_time']);
            $end_time = strtotime($post['end_time']);
            $where['payment_time'] = array(array('egt', $start_time), array('lt', $end_time), 'and');
        } else {
            if ($post['start_time']) {
                $start_time = strtotime($post['start_time']);
                $where['payment_time'] = array('egt', $start_time);
            }
            if ($post['end_time']) {
                $end_time = strtotime($post['end_time']);
                $where['payment_time'] = array('lt', $end_time);
            }
        }
        $this->assign('start_time', $post['start_time']);
        $this->assign('end_time', $post['end_time']);
        //}

        if ($post['yushou_order_type'] > 0) {
            if ($post['yushou_order_type'] == 1) {
                $where['orders.product_dingjin'] = array('gt', 0);
            } else {
                $where['orders.product_dingjin'] = 0;
            }
        }


        if ($_POST['dosubmit']) {
            $where = 1;
            if ($_POST['order_sn'])
                $where .= ' AND order_sn like "%' . $_POST['order_sn'] . '%"';
            if ($_POST['delivery_email'])
                $where .= ' and delivery_email like "%' . $_POST['delivery_email'] . '%"';
            if ($_POST['delivery_name'])
                $where .= ' and delivery_name like "%' . $_POST['delivery_name'] . '%"';
            if ($_POST['delivery_postcode'])
                $where .= ' and delivery_postcode like "%' . $_POST['delivery_postcode'] . '%"';
            if ($_POST['delivery_phone'])
                $where .= ' and delivery_phone like "%' . $_POST['delivery_phone'] . '%"';
            if ($_POST['delivery_mobile'])
                $where .= ' and delivery_mobile like "%' . $_POST['delivery_mobile'] . '%"';
            if ($_POST['delivery_cid'] > 0)
                $where .= ' and delivery_cid = "' . $_POST['delivery_cid'] . '"';
            if ($_POST['delivery_province'])
                $where .= ' and delivery_province like "%' . $_POST['delivery_province'] . '%"';
            if ($_POST['delivery_city'])
                $where .= ' and delivery_city like "%' . $_POST['delivery_city'] . '%"';
            if ($_POST['shipping_method'] > 0)
                $where .= ' and shipping_method = "' . $_POST['shipping_method'] . '"';
            if ($_POST['payment_method'] > 0)
                $where .= ' and payment_method = "' . $_POST['payment_method'] . '"';
            if ($_POST['start_time1'] && $_POST['start_time2']) {
                $where .= ' and start_time >"' . $_POST['start_time1'] . '" and start_time <= "' . $_POST['start_time2'] . '"';
            }
            if ($_POST['order_status'] > 0)
                $where .= ' and order_status =' . $_POST['order_status'] . '';
            if ($_POST['payment_status'] > 0)
                $where .= ' and payment_status =' . $_POST['payment_status'] . '';
            if ($_POST['shipping_status'] > 0)
                $where .= ' and shipping_status =' . $_POST['shipping_status'] . '';
            if ($_POST['delivery_address']) {
                $where .= ' and (delivery_address like "%' . $_POST['delivery_address'] . '%" or delivery_address2 like "%' . $_POST['delivery_address'] . '%" or delivery_address3 like "%' . $_POST['delivery_address'] . '%" or delivery2_address like "%' . $_POST['delivery_address'] . '%" or delivery2_address2 like "%' . $_POST['delivery_address'] . '%" or delivery2_address3 like "%' . $_POST['delivery_address'] . '%")';
            }
        }
        $order_db = D('orders');

        $pageRows = 20;
        if (isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])) {
            $pageRows = intval($_REQUEST['pageRows']);
        }
        if (!isset($post['order_status']) || $post['order_status'] != OrderModel::ORDER_DEL) {
            $where['_string'] = ' order_status !=' . OrderModel::ORDER_DEL;
        }

        $order_db = D('orders');
        $order_List = $order_db->where($where)->order('id desc')->select();
		
        import('COM.XmlExcel');
        $excel = new XmlExcel;
        $excel_title = array('收货人姓名', '邮箱', '订单号', '使用语言', '下单时间', '付款时间', '更新时间', '订单总金额', '应付金额','联系方式','地址信息');
        $excel->setSheetHead($excel_title, '中文订单'); //设置CSV文件标题

        foreach ($order_List as $key => $value) {
            $language = "";
            if ($value['user_id'] > 0) {
                $language = D('language')->where(array('id' => $value['language_id']))->getField('name');
            }

            $addRowData = array(
                $value['delivery_first_name'] . $value['delivery_last_name'],
                $value['delivery_email'],
                $value['order_sn'],
                $language,
                date('Y-m-d H:i:s', $value['start_time']),
                $value['payment_time'] ? date('Y-m-d H:i:s', $value['payment_time']) : '',
                $value['update_time'] ? date('Y-m-d H:i:s', $value['update_time']) : '',
                $value['order_amount'],
                $value['pay_amount'],
				$value['delivery_phone'],
				'['. $value['delivery_country'] . ($value['delivery_province'] ? ' - '.$value['delivery_province'] : null). ' ] '. $value['delivery_address'].$value['delivery_address2'].$value['delivery_address3'],
				
            );
            $excel->addRow($addRowData, '中文订单');

        }

        foreach ($order_List as $key => $value) {
            $language = "";
            if ($value['user_id'] > 0) {
                $language = D('language')->where(array('id' => $value['language_id']))->getField('name');
            }

            $Data = array(
                $value['delivery_first_name'],
                $value['delivery_last_name'],
                $value['delivery_email'],
                $value['delivery_phone'],
                $value['delivery_address'] . ' ' . $value['delivery_address2'],
                $value['delivery_city'],
                $value['delivery_province'],
                $value['delivery_postcode'],
                $value['order_sn'],
                $value['start_time'] ? date('Y-m-d H:i:s', $value['start_time']) : '',
                $value['payment_time'] ? date('Y-m-d H:i:s', $value['payment_time']) : '',
                $value['order_amount'],
                $value['pay_amount']
            );
            $engilish_list[] = $Data;

        }
        $excel_title = array('First Name', 'Last Name', 'Email', 'Telephone', 'Address', 'City', 'State', 'Zip Code', 'Order number', 'Date of order', 'Date of payment', 'Amount', 'Payment');
        $excel->setSheetHead($excel_title, 'english');
        $excel->addRows($engilish_list, 'english');


        //商品及面料统计表
        $pidArr = array();
        foreach ($order_List as $key => $value) {
            $itemsPid = D('orders_items')->field('product_id,qty')
                ->where('order_id=' . $value['id'])->select();
            foreach ($itemsPid as $val) {
                if (isset($pidArr[$val['product_id']])) {
                    $pidArr[$val['product_id']] += $val['qty'];
                } else {
                    $pidArr[$val['product_id']] = $val['qty'];
                }
            }
        }

        arsort($pidArr);

        $kk = 1;
        foreach ($pidArr as $pid => $num) {
            $product = D('product')->field('catid,suppliers_id')->where('id=' . $pid)->find();
            if (!$product) continue;
            $parentid = D('category')->where('id=' . $product['catid'])->getField('parentid');
            $catid = $parentid > 0 ? $parentid : $product['catid'];
            $category_name = D('category_items')->where(array('category_id' => $catid, 'language_id' => 1))->getField('name');
            $suppliers = D('suppliers')->field('suppliers_name,lining_name')->where(array('suppliers_id' => $product['suppliers_id']))->find();
            $Data = array(
                $kk,
                $pid,
                $category_name,
                $num,
                $suppliers['suppliers_name'],
                $suppliers['lining_name'],
            );
            $statistics_list[] = $Data;
            $kk++;
        }

        $excel_title = array('序号', '商品ID', '商品类型', '销售数量', '面料编号', '面料成分');
        $excel->setSheetHead($excel_title, '商品及面料统计表');
        $excel->addRows($statistics_list, '商品及面料统计表');
        
        //销售量统计单页
        $excel_title = array('序号', '订单号', ' 商品ID', '价格', '分类', '类型属性', '花型', '颜色', '面料编号', '面料成分', '领形', '扣型');
        $excel->setSheetHead($excel_title, '销售量统计单页');
        //分类数据
        $categoryList = array();            
        $categoryListRes = CategoryModel::getCategoryList(1);
        foreach ($categoryListRes as $category) {
            $categoryList[$category['id']] = $category;
        }            
        $categoryListRes = CategoryModel::getCategoryList(8);
        foreach ($categoryListRes as $category) {
            $categoryList[$category['id']] = $category;
        }                       
        $categoryListRes = CategoryModel::getCategoryList(9);
        foreach ($categoryListRes as $category) {
            $categoryList[$category['id']] = $category;
        }                       
        $categoryListRes = CategoryModel::getCategoryList(11);
        foreach ($categoryListRes as $category) {
            $categoryList[$category['id']] = $category;
        }                       

        $num = 1;
        foreach ($order_List as $key => $value) {
            $orders_items = D('orders_items')->field('*')
                ->where('order_id=' . $value['id'])->select();
            foreach ($orders_items as $item) {
               $product = D('product')->field('*')
                ->where('id=' . $item['product_id'])->find();  
                //销售价格         
                if($product['attribute_type']==1){
                    $price_sale = $product['custom_price'];
                }else{
                    $price_sale = $product['advanced_price'];                        
                }
                //分类id
                $parentid = CategoryModel::get_category_parentid($product['catid']); 
                $cid = $parentid > 0 ? $parentid : $product['catid'];
                //分类属性
                $category_id = explode(",",$product['category_id']); 
                $category_attr = "";
                foreach ($category_id as $id) {
                    if($category_attr) $category_attr .= ',';                              
                    $category_attr .= $categoryList[$id]['name'];  
                }
                //花型
                $colour_id = explode(",",$product['colour_id']); 
                $colour = "";
                foreach ($colour_id as $id) {
                    if($colour) $colour .= ',';                        
                    $colour .= $categoryList[$id]['name'];  
                }
                //颜色
                $product_colour_id = explode(",",$product['product_colour_id']); 
                $product_colour = "";
                foreach ($product_colour_id as $id) {
                    if($product_colour) $product_colour .= ',';
                    $product_colour .= $categoryList[$id]['name'];  
                }
                //面料编号、面料成分、领形、扣型
                $suppliers_name       = '';
                $suppliers_ingredient = '';
                $lapel_name = '';
                $button_name = '';
                if( intval($product['suppliers_id']) > 0 )
                {
                    $suppliers = SuppliersModel::getSuppliersInfo($product['suppliers_id']);
                    $suppliers_name       = $suppliers['suppliers_name'];
                    $suppliers_ingredient = $suppliers['lining_name'];                   
                } 

                $Lapel  = 0;
                $button = 0;
                if ($product['model_id'] == 2) { //两件套
                    $Lapel  = 22; //两件套领型
                    $button = 25; //两件套扣型
                } elseif ($product['model_id'] == 18) {//三件套
                    $Lapel  = 93; //三件套领型
                    $button = 95; //三件套扣型
                } elseif ($product['model_id'] == 14) {//衬衫
                    $Lapel  = 56; //衬衫领型
                    $button = 0; //衬衫扣型  
                } elseif ($product['model_id'] == 20) {//马甲
                    $Lapel  = 126; //马甲领型
                    $button = 127; //马甲扣型
                } elseif ($product['model_id'] == 1) {//单西
                    $Lapel  = 2; //单西领型
                    $button = 4; //单西扣型
                }                                 
                if($Lapel || $button){
                    //商品类型
                    $orderfigure = OrderModel::orderPrintFigure($item['id']); 
                    if($Lapel){
                        $lapel_name = $orderfigure['attr_array'][$Lapel]['cn_attr_value_name'];
                    }   
                    if($button){
                        $button_name = $orderfigure['attr_array'][$button]['cn_attr_value_name'];                  
                    } 
                }
                $addRowData = array(
                    $num,
                    $value['order_sn'],
                    $item['product_id'],
                    $price_sale,
                    $categoryList[$cid]['name'],
                    $category_attr,
                    $colour,
                    $product_colour,
                    $suppliers_name,
                    $suppliers_ingredient,
                    $lapel_name,
                    $button_name,
                );
                $excel->addRow($addRowData, '销售量统计单页');
                $num++;
            }
        }
        
        //商品结算清单
        $num = 1;
        $addSellRowDatas = array();
        foreach ($order_List as $key => $value) {
            $orderInfo = D('orders')->field('*')
                ->where('id=' . $value['id'])->find();            
            $orders_items = D('orders_items')->field('*')
                ->where('order_id=' . $value['id'])->select();
            foreach ($orders_items as $item) {
                $product_info = D('product')->field('*')
                ->where('id=' . $item['product_id'])->find();
                if(!in_array($product_info['model_id'], array(1,2,18,20,21,22,23))){
                   continue; 
                }                  
                //获取分类 
                $catid = $product_info['catid'];
                $parentid = D('category')
                    ->where(array('id' => $catid))
                    ->getField('parentid');
                if ($parentid > 0) $catid = $parentid;                 
                //商品类型
                $orderfigure = OrderModel::orderPrintFigure($item['id']);
                $Blazer = '';
                $Pants  = '';
                $Vest   = '';
                $Coat   = '';
                $fullDress   = '';
                $half        = '';
                $patchPocket = '';
                $font = '';
                $slit = '';
                $theSmartBag   = '';
                $adjustableTab = '';
                $picStitch     = '';
                $chest         = '';
                $shoulder      = '';
                $Sleeve        = '';
                $adhesive      = '';
                $collarFloor   = '';    
                $grid   = '';
                $stripe = '';          
                //判断绣字
                list($font_1_key, $font_2_key, $font_zt_key, $font_color_key) = OrderModel::font_key($orderfigure, $product_info['model_id']);
                $font_1 = isset($orderfigure['attr_array'][$font_1_key]) ? $orderfigure['attr_array'][$font_1_key]['cn_attr_value_name'] : '';  //第一行
                $font_2 = isset($orderfigure['attr_array'][$font_2_key]) ? $orderfigure['attr_array'][$font_2_key]['cn_attr_value_name'] : '';  //第二行                
                if($font_1 || $font_2){
                     $font = 1;
                }
                //判断格子 条纹
                $figure = D('suppliers')->where(array('suppliers_id' => $product_info['suppliers_id']))->getField('figure');
                if( $figure == 1 ){ $grid   = '1'; } //格子
                if( $figure == 2 ){ $stripe = '1'; } //条纹
                //模型
                if ($product_info['model_id'] == 2) {         //两件套
                    $Blazer = '1';$Pants = '1';
                    $half = $this->attrCompare($orderfigure,34,100); //半里
                    $patchPocket = $this->attrCompare($orderfigure,26,81);  //贴袋
                    if(isset($orderfigure['attributes_more_array'][136])){
                        $slit = $this->attrCompareOption($orderfigure,136); //袖叉
                    }
                    if(isset($orderfigure['attributes_more_array'][137])){
                        $theSmartBag = $this->attrCompareOption($orderfigure,137); //智能袋
                    }
                    if(isset($orderfigure['attributes_more_array'][132])){
                        $adjustableTab = $this->attrCompareOption($orderfigure,132);  //调节袢
                    }
                    if(isset($orderfigure['attributes_more_array'][138])){
                        $picStitch = $this->attrCompareOption($orderfigure,138); //珠边
                    }         
                } elseif ($product_info['model_id'] == 18) {  //三件套
                    $Blazer = '1';$Pants = '1';$Vest = '1';
                    $half        = $this->attrCompare($orderfigure,104,313); //半里
                    $patchPocket = $this->attrCompare($orderfigure,96,294);  //贴袋
                    $slit        = $this->attrCompareOption($orderfigure,342); //袖叉
                    $theSmartBag   = $this->attrCompareOption($orderfigure,343); //智能袋
                    $adjustableTab = $this->attrCompareOption($orderfigure,339); //调节袢
                    $picStitch     = $this->attrCompareOption($orderfigure,344); //珠边

                } elseif ($product_info['model_id'] == 14) {  //衬衫

                } elseif ($product_info['model_id'] == 20) {  //马甲
                    $Vest = '1';
                } elseif ($product_info['model_id'] == 21) {  //裤子
                    $Pants = '1';
                    $adjustableTab = $this->attrCompareOption($orderfigure,640); //调节袢

                } elseif ($product_info['model_id'] == 1) {   //单西
                    $Blazer = '1';
                    $half        = $this->attrCompare($orderfigure,68,202); //半里
                    $patchPocket = $this->attrCompare($orderfigure,60,183);  //贴袋
                    $slit        = $this->attrCompareOption($orderfigure,210); //袖叉
                    $theSmartBag = $this->attrCompareOption($orderfigure,211); //智能袋
                    $picStitch   = $this->attrCompareOption($orderfigure,212); //珠边  
                    $chest       = '1'; //胸衬
                    $shoulder    = '1'; //垫肩
                    $Sleeve      = '1'; //弹袖条
                    $adhesive    = '1'; //粘合衬
                    $collarFloor = '1'; //领底呢                
                } elseif ($product_info['model_id'] == 22) {  //大衣
                    $Coat = '1';
                } elseif ($product_info['model_id'] == 23) {  //礼服
                    //特俗礼服处理
                    $fullDress = '1';
                    $slit      = '1'; //袖叉
                    // if ($catid == 2093) 两件套;
                    // if ($catid == 2061) 三件套;
                }                     

                //礼服
                $full_dress_pid_arr = array(
                    384,383,374,369,372,370,371,373,
                    389,390,391,394,392,396,393,395,
                    561,559,
                    562,560,
                );
                if(in_array($item['product_id'], $full_dress_pid_arr)){
                    $fullDress = '1';
                }
                $isSwallowtail =  in_array($item['product_id'], array(371,393)) ? '1' : '';//燕尾服
                $addSellRowData = array(
                    $num, //序号
                    '',  //流水号
                    date('Y-m-d',$orderInfo['start_time']), //下单日期
                    $orderInfo['id'].'-'.$item['id'], //乐尚订单号
                    $Blazer,     //上衣
                    $Pants,      //西裤
                    $Vest,       //马甲
                    $Coat,       //大衣
                    $fullDress,  //礼服
                    $half,       //半里
                    $patchPocket,//贴袋
                    $font,       //绣字
                    $slit,       //真叉
                    $half,       //滚边 同半里，有半里就有滚边
                    $theSmartBag,   //智能袋
                    $adjustableTab, //调节袢
                    $grid,        //格子
                    $stripe,      //条子
                    $picStitch,   //珠边
                    $chest,       //胸衬
                    $shoulder,    //垫肩
                    $Sleeve,      //弹袖条
                    $adhesive,    //粘合衬
                    $collarFloor, //领底呢
                    '', //袋布
                    '', //全身明切（珠边）
                    $isSwallowtail, //燕尾服
                    '', //立领
                    '', //付款金额
                    '', //付款日期
                    '', //交货日期
                );
                $addSellRowDatas[] = $addSellRowData;
                $num++;            
            }
        }
        $excel_title = array('序号', '流水号', '下单日期', '乐尚订单号', '上衣','西裤','马甲','大衣','礼服','半里','贴袋','绣字','真叉','滚边','智能袋','调节袢','格子','条子','珠边','胸衬','垫肩','弹袖条','粘合衬','领底呢','袋布','全身明切（珠边）','燕尾服','立领','付款金额','付款日期','交货日期');
        $excel->setSheetHead($excel_title, '商品结算清单'); 
        $excel->addRows($addSellRowDatas, '商品结算清单');

        $excel->setDefaultWidth(100);
        $excel->export('order_list');

    }
    //判断定制选项是否存在
    public function attrCompare($orderfigure, $attr_id, $attr_value_id)
    {
        if($orderfigure['attr_array'][$attr_id]['attr_value_id'] == $attr_value_id){
           return 1;              
        }
        return '';
    }
    //判断option定制选项是否存在
    public function attrCompareOption($orderfigure,$attr_value_id)
    {
        if(isset($orderfigure['attributes_more_array'][$attr_value_id])){
           return 1;              
        }
        return '';
    }    
    //欺诈信息列表
    public function order_cheat_list()
    {
        $where = array();
        $order_by = $_REQUEST['order'];

        //order by
        if (isset($_REQUEST['sort_by']) && $_REQUEST['sort_by']) {
            $sort_by = $_REQUEST['sort_by'];
        } else {
            $sort_by = 'DESC';
        }

        if (isset($_REQUEST['order_by']) && $_REQUEST['order_by']) {
            $order_by = $_REQUEST['order_by'];
        } else {
            $order_by = 'id';
        }
        $order_cheat_db = D('orders_cheat');

        $pageRows = 20;
        if (isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])) {
            $pageRows = intval($_REQUEST['pageRows']);
        }

        //分页
        $order_cheat_db->where($where);
        $count = $order_cheat_db->count();//总记录数
        import("ORG.Util.Page");// 导入分页类
        $Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
        $pageShow = $Page->show();// 分页显示输出
        $this->assign('pageShow', $pageShow);

        $order_cheat_db->limit($Page->firstRow . ',' . $Page->listRows);
        $order_cheat_db->where($where);
        $cheatList = $order_cheat_db->order($order_by . ' ' . $sort_by)->select();

        $this->assign('order', $order);
        $this->assign('cheatList', $cheatList);
        $this->assign('sort_by', $sort_by);
        $this->assign('order_by', $order_by);
        $this->display('order_cheat_list');
    }

    //编辑欺诈信息
    public function order_cheat_edit()
    {
        $chid = intval($_GET['chid']);

        $order_cheat_db = D('orders_cheat');
        if ($_POST['dosubmit']) {
            $order_cheat_db->create();
            if ($chid) {
                $order_cheat_db->where('id=' . $chid)->save();
            } else {
                $order_cheat_db->add();
            }
            S('order_cheat_list', NULL);
            $this->success('操作成功', U('order/order_cheat_list'));
        } else {
            $cheatInfo = array();
            if ($chid) {
                $cheatInfo = $order_cheat_db->find($chid);
            }
            $this->assign('cheatInfo', $cheatInfo);
            $this->display('order_cheat_edit');
        }
    }

    //删除欺诈信息
    public function order_cheat_delete()
    {
        $chid = intval($_GET['chid']);
        $order_cheat_db = D('orders_cheat');
        $order_cheat_db->delete($chid);
        S('order_cheat_list', NULL);
        $this->success('操作成功', U('order/order_cheat_list'));
    }

    public function order_down_invoice()
    {
        if ($_POST['dosubmit']) {
            $down_type = intval($_POST['down_type']);
            $payment_time = array(array('gt', strtotime($_POST['start_date'])), array('lt', strtotime($_POST['end_date'] . ' 23:59:59')), 'AND');
            if ($down_type == 1) {
                $where['payment_method'] = 'Ips';
                $where['payment_time'] = $payment_time;
            } elseif ($down_type == 2) {
                $where['payment_method'] = array('in', 'Visabill,Visabillnew');
                $where['payment_time'] = $payment_time;
            } elseif ($down_type == 3) {
                //$where['payment_method'] = '';
                $where['payment_time'] = $payment_time;
            } elseif ($down_type == 4) {
                $where['order_sn'] = array('in', implode(',', explode("\n", str_replace("\r", '', $_POST['ordersn']))));
            }

            $order_db = D('orders');
            $orders_delivery_db = D('orders_delivery');
            $orderList = $order_db->field('order_sn,id,payOrderNum,shipping_method')->where($where)->select();
            if ($orderList) {
                foreach ($orderList as $key => $order) {
                    $shipping_no = $orders_delivery_db->where(array('order_id' => $order['id']))->getField('shipping_no');
                    $orderList[$key]['shipping_no'] = $shipping_no ? $shipping_no : '配货中';
//					echo $orders_delivery_db->getLastsql().'<br/>';
                }
            } else {
                if ($down_type != 4)
                    $this->error('无发货单', U('order/order_down_invoice'));
            }
            $shippingUrlArray = array(
                'ems' => 'http://www.ems.com.cn',
                'ups' => 'http://www.ups.com'
            );

            if ($down_type == 4) {

                foreach ($orderList as $order) {
                    $shippingNo = explode(',', $order['shipping_no']);
                    $orderSn[$order['order_sn']]['shipping_no'] = $shippingNo[0];
                }
                $order_sns = explode(',', $where['order_sn'][1]);
                foreach ($order_sns as $orders) {
                    $shippingNo = $orderSn[$orders]['shipping_no'];
                    if (!$shippingNo)
                        $shippingNo = '配货中';
                    echo $shippingNo . "<br>";
                }
                /*foreach ($orderList as $order){
					//echo '订单号：'.$order['order_sn'] . ' 快递号：' .$order['shipping_no'].'<br/>';
					$shippingNo = explode(',',$order['shipping_no']);
					echo $shippingNo[0].'<br/>';
				}*/
                exit;
            } else {
                import('COM.XmlExcel');
                $xls = new XmlExcel;
                $xls->addHead(array('支付单号', '订单号', '物流单号', '物流网址'));
                foreach ($orderList as $order) {
                    $xls->addRow(array($order['payOrderNum'], $order['order_sn'], $order['shipping_no'], $shippingUrlArray[$order['shipping_method']]));
                }
                $xls->export("order_invoice");
            }
        } else {
            $this->display('order_down_invoice');
        }
    }


    /**
     * 设计师订单列表
     */
    public function order_designer_list()
    {
        $where = array();
        $post = $_REQUEST;
        //搜索订单状态
        if (isset($post['order_status']) && $post['order_status'] != 9999) {
            $where['orders.order_status'] = $post['order_status'];
        }
        //搜索支付状态
        if (isset($post['payment_status']) && $post['payment_status'] != 9999) {
            $where['orders.payment_status'] = $post['payment_status'];
        }
        //搜索配送状态
        if (isset($post['shipping_status']) && $post['shipping_status'] != 9999) {
            $where['orders.shipping_status'] = $post['shipping_status'];
        }
        //搜索关键词
        if (isset($post['order_sn']) && $post['order_sn']) {
            $where['orders.order_sn'] = $post['order_sn'];
        }
        if (isset($post['designer_id']) && $post['designer_id'] != -1) {
            $where['oi.designer_id'] = intval($post['designer_id']);
        }

        $order_db = D('orders');
        $order_items_db = D('orders_items oi');

        //分页
        $order_items_db->where($where);
        $order_items_db->join('orders ON orders.id=oi.order_id');
        $order_items_db->where($where)->group('order_id');
        $count = $order_items_db->count();
        import("ORG.Util.Page");
        $Page = new Page($count, 20);
        $pageShow = $Page->show();
        $this->assign('pageShow', $pageShow);

        $order_items_db->field('orders.id,order_sn,order_status,payment_status,shipping_status,orders.start_time');
        $order_items_db->join('orders ON orders.id=oi.order_id');
        $order_items_db->where($where)->group('order_id');
        $order_items_db->order('orders.id DESC');
        $order_items_db->limit($Page->firstRow . ',' . $Page->listRows);
        $orderList = $order_items_db->select();
//		echo $order_items_db->getLastSql();exit;
        if ($orderList) {
            foreach ($orderList as &$order) {
                $oiwhere['oi.order_id'] = $order['id'];
                if (isset($where['oi.designer_id'])) {
                    $oiwhere['oi.designer_id'] = $where['oi.designer_id'];
                } else {
                    $oiwhere['oi.designer_id'] = array('gt', 0);
                }
                $order_items_db->field('oi.product_id,oi.designer_id,oi.product_sn,oi.product_name,oi.sell_price,oi.qty,total_amount,attr,custom_type,product.small_img,users.username');
                $order_items_db->join('product ON product.id=oi.product_id');
                $order_items_db->join('users ON oi.designer_id=users.id');
                $order_items_db->where($oiwhere);
                $productList = $order_items_db->select();
//				echo $order_items_db->getLastSql();exit;
                if ($productList) {
                    foreach ($productList as &$product) {
                        if ($product['attr']) {
                            $data = unserialize($product['attr']);
                            if ($data) {
                                $attributes = array();
                                if ($product['custom_type']) {
                                    foreach ($data as $vk => $val) {
                                        $attributes[] = $val['attr_name'] . ':' . $val['attr_value'];
                                    }
                                } else {
                                    foreach ($data as $vk => $val) {
                                        $attributes[] = $vk . ':' . $val;
                                    }
                                }
                                $attribute = implode(' , ', $attributes);
                            }
                            $product['attr'] = $attribute;
                        }
                    }
                    unset($product);
                }
                $order['productList'] = $productList;
            }
        }
        unset($order);// 最后取消掉引用

        $this->assign('orderList', $orderList);
        $this->assign('search', isset($post) && $post ? $post : null);
        //设计师列表
        $designerList = UserModel::getUserDesignerList();
        $this->assign('designerList', $designerList);
        $this->display('order_designer_list');
    }

    //处理订单信息（预售时间）
    public function automatic_order()
    {
        //查看订单状态
        $order_db = D('orders');
        $order_db->join('orders_items ON orders_items.order_id = orders.id');
        $orderList = $order_db->field('orders.id,orders.order_status,orders.payment_status,orders.order_amount,orders.integral_money,orders.integral,orders.pay_integral,orders.user_id,orders.order_sn,orders_items.product_id,orders_items.qty')->where('orders_items.car_type=1 AND orders.order_status between 0 and 1')->select();
        foreach ($orderList as $product) {
            $product_db = D('product');
            $productInfo = $product_db->field('id,yushou_end_time,refund,yufu_price')->where('id=' . $product['product_id'])->find();
            //获取购买该产品的数量(预售)
            $orders_db02 = D('orders');
            $orders_db02->field('sum(orders_items.qty) as number');
            $orders_db02->join('orders_items ON orders_items.order_id = orders.id');
            $number = $orders_db02->where('orders_items.product_id=' . $product['product_id'] . ' AND orders.payment_status=1 AND orders_items.car_type=1')->find();

            //预售时间已过且未付款则取消订单
            if (time() >= $productInfo['yushou_end_time']) {
                if ($product['payment_status'] == 0) {
                    $data['order_status'] = -1;
                    $result = $order_db->where('id=' . $product['id'])->save($data);
                }
                if ($product['payment_status'] == 1) {
                    //先判断其商品是否团购
                    $wholesale = PromotionModel::get_product_wholesale_info($productInfo['id']);
                    //如果是团购的话，没满足团购条件则退款
                    if ($wholesale['display'] > 0) {
                        $prices = unserialize($wholesale['prices']);
                        for ($i = 0; $i < count($prices); $i++) {
                            if ($number['number'] >= $prices[1]['qty'])
                                $product_price = $prices[1]['price'];
                            else
                                $product_price = 0;
                        }
                    }
                    if ($product_price == 0) {
                        //退款，退积分
                        if ($product['user_id']) {
                            if ($productInfo['refund']) {
                                $return_amount = $product['order_amount'] - $product['integral_money'] - $product['qty'] * $productInfo['yufu_price'];
                            } else {
                                $return_amount = $product['order_amount'] - $product['integral_money'];
                            }
                            UserModel::logAccountChange($product['user_id'], $return_amount, 0, 0, $product['integral'], '预售订单退款，订单号为' . $product['order_sn'], UserModel::ACT_REFUND);
                            if ($product['pay_integral']) {
                                //退还赠送积分
                                UserModel::logAccountChange($product['user_id'], 0, 0, 0, (-1) * $product['pay_integral'], L('gift_points') . ' ' . L('order number : ') . $payInfo['order_sn'], UserModel::ACT_REFUND);
                            }

                            //取消订单
                            $data['order_status'] = -1;
                            $result = $order_db->where('id=' . $product['id'])->save($data);

                            $orderInfo = OrderModel::get_order_info($product['id']);
                            $data['admin_note'] .= '<br/>' . L('_ALREADY_BACK_INTO_BALANCE_');
                            $email_template = UserModel::get_email_template_info('payReturnEmail', $orderInfo['language_id']);
                            //发邮件
                            if ($email_template) {
                                $mailInstance = new EmailModel();
                                $content = str_replace('{$user_name}', $orderInfo['delivery_first_name'] . ' ' . $orderInfo['delivery_last_name'], $email_template['content']);
                                $content = str_replace('{$admin_note}', $data['admin_note'], $content);
                                $title = str_replace('{$order_sn}', $orderInfo['order_sn'], $email_template['title']);
                                $content = $mailInstance->replaceMail($content);
                                $title = $mailInstance->replaceMail($title);
                                $mailInstance->sendMail($orderInfo['delivery_email'], $title, $content);
                            }
                        }
                    }
                }

            }

            echo "已处理订单号：" . $product['id'] . "<br>";

        }

    }

    //用户购物车查看
    public function cart_product()
    {
        $post = $_REQUEST;
        $where = array();

        //搜索关键词
        if (isset($post['keyword']) && $post['keyword']) {
            if ($post['searchtype'] == 0) {
                $where['users.email'] = $post['keyword'];
            } else if ($post['searchtype'] == 1) {
                $where['sid'] = $post['keyword'];
            }
            $this->assign('searchtype', $post['searchtype']);
            $this->assign('searchkeyword', $post['keyword']);
        }

        if (!isset($post['usertype']) || ($post['usertype'] != 2 && $post['usertype'] != 3)) {
            $post['usertype'] = 1;
        }

        if ($post['usertype'] == 1) {
            $where['user_id'] = array('GT', 0);
        } else if ($post['usertype'] == 3) {
            $where['user_id'] = 0;
        }
        $this->assign('usertype', $post['usertype']);

        //语言
        if (intval($post['language']) > 0) {
            $where['language_id'] = intval($post['language']);
        }
        $this->assign('language', $post['language']);

        $where['_string'] = '';
        //开始时间
        if (!empty($post['start_time'])) {
            $where['_string'] .= ' add_time >= ' . strtotime($post['start_time'] . " 00:00:00");
        }
        $this->assign('start_time', $post['start_time']);

        //开始时间
        if (!empty($post['end_time'])) {
            $where['_string'] .= ' and add_time <= ' . strtotime($post['end_time'] . " 23:59:59");
        }
        $this->assign('end_time', $post['end_time']);

        if (empty($where['_string'])) unset($where['_string']);
        //print_r($where);

        $cart_product_db = D('cart_products as cart');

        //excel daochu
        if (intval($post['doexcel']) == 1) {

            $cart_product_db->join('users ON users.id = cart.user_id');
            $cart_product_db->field('users.first_name,users.last_name,users.reg_time,users.email,users.language_id,cart.user_id,cart.sid,max(cart.add_time) as add_time,
				count(cart.id) as counts,sum(cart.qty) as qtys,IF(cart.user_id=0, cart.sid ,0) as sidss');
            $cart_product_db->order('cart.id desc');
            $cart_product_db->where($where);
            $cart_product_db->group('cart.user_id,sidss');
            $cartList = $cart_product_db->select();
            //echo M()->getLastsql();

            //获取身型字段
            $measure_field = MeasureModel::user_measure_field();

            $measure_infos_field = "";
            foreach ($measure_field as $val) {
                $measure_infos_field .= ',' . $val['measure_field'];
            }
            import('COM.XmlExcel');
            $excel = new XmlExcel;
            $excel_title = array('姓名', 'Email', '语言', '注册时间', '更新购物车时间', '加入购物车产品', '购物车总金额', '量体方式', '身形信息');
            foreach ($measure_field as $mfield) {

                $excel_title[] = $mfield['measure_field'];
            }
            $excel->addHead($excel_title); //设置CSV文件标题

            foreach ($cartList as $key => $value) {
                $language = "";
                if ($value['user_id'] > 0) {
                    $language = D('language')->where(array('id' => $value['language_id']))->getField('name');
                }

                $c_user = array(
                    'id' => $value['user_id'],
                    'sid' => $value['sid']
                );
                $productList = OrderModel::get_cart_product_list(false, 0, $c_user);

                $addRowData = array(
                    $value['first_name'] . $value['last_name'],
                    $value['email'],
                    $language,
                    date('Y-m-d H:i:s', $value['reg_time']),
                    date('Y-m-d H:i:s', $value['add_time']),
                    '↓商品链接↓',
                    $productList['total_amount'],
                    '',
                );
                foreach ($measure_field as $mfield) {
                    $addRowData[] = '';
                }

                $excel->addRow($addRowData);

                foreach ($productList['productList'] as $vp) {
                    $addRowData = array(
                        '',
                        '',
                        '',
                        '',
                        '',
                        'http://www.ownonly.com' . $vp['product']['url'],
                        '',
                    );
                    if (intval($vp['measure_id']) > 0) {
                        $measure_infos = M('user_measure')->field('user_id,measure_name,measure_data,update_time ' . $measure_infos_field)->where('id=' . $vp['measure_id'])->find();
                        $m_status_info = M('user_measure')->field('m_status')->where('id=' . $vp['measure_id'])->find();
                        switch ($m_status_info['m_status']) {
                            case 1:
                                $m_status = '量尺量体';
                                break;
                            case 2:
                                $m_status = '免量体';
                                break;
                            case 3:
                                $m_status = '拍照量体';
                                break;
                            case 4:
                                $m_status = '量尺并拍照';
                                break;
                        }
                        $addRowData[] = $m_status;
                        $addRowData[] = $measure_infos['measure_name'];
                        foreach ($measure_field as $mfield) {
                            $measure_field_val = $measure_infos[$mfield['measure_field']];
                            if ($mfield['field_type'] != 'type') $measure_field_val .= $mfield['field_type'];
                            $addRowData[] = $measure_field_val;
                        }
                    } else {
                        $addRowData[] = '';
                        foreach ($measure_field as $mfield) {
                            $addRowData[] = '';
                        }
                    }
                    $excel->addRow($addRowData);
                }
            }

            $excel_name = '已加入购物车数据' . '-' . date('Y-m-d H:i');
            $excel->export($excel_name);
            exit;
        }


        $pageRows = 20;
        if (isset($_REQUEST['pageRows']) && intval($_REQUEST['pageRows'])) {
            $pageRows = intval($_REQUEST['pageRows']);
        }
        //分页
        $cart_product_db->join('users ON users.id = cart.user_id');
        $cart_product_db->field('IF(cart.user_id=0, cart.sid ,0) as sidss');
        $cart_product_db->order('cart.id desc');
        $cart_product_db->where($where);
        $cart_product_db->group('cart.user_id,sidss');
        $cartList = $cart_product_db->select();
        $count = count($cartList);//总记录数
        import("ORG.Util.Page");// 导入分页类
        $Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
        $pageShow = $Page->show();// 分页显示输出
        $this->assign('pageShow', $pageShow);

        $cart_product_db->join('users ON users.id = cart.user_id');
        $cart_product_db->field('users.email,users.language_id,cart.user_id,cart.sid,max(cart.add_time) as add_time,
			count(cart.id) as counts,sum(cart.qty) as qtys,IF(cart.user_id=0, cart.sid ,0) as sidss');
        $cart_product_db->order('cart.id desc');
        $cart_product_db->where($where);
        $cart_product_db->group('cart.user_id,sidss');
        $cart_product_db->limit($Page->firstRow . ',' . $Page->listRows);
        $cartList = $cart_product_db->select();
        //echo M()->getLastsql();;

        foreach ($cartList as $key => $value) {
            if ($value['user_id'] > 0) {
                $cartList[$key]['language'] = D('language')->where(array('id' => $value['language_id']))->getField('name');
            }
            $c_user = array(
                'id' => $value['user_id'],
                'sid' => $value['sid']
            );
            $cartList[$key]['productList'] = OrderModel::get_cart_product_list(false, 0, $c_user);
        }

        //语言列表
        $languageList = SiteModel::getLanguageList();
        $this->assign('countryList', $languageList);

        // var_dump($cartList[0]['productList']);die;
        $this->assign('cartList', $cartList);
        $this->assign('pageRows', $pageRows);
        $this->display('cart_product');

    }

//订单查询
    public function order_query()
    {
        //国家列表
        $countryList = SiteModel::getCountryList();
        $this->assign('countryList', $countryList);
        $paymentList = PaymentModel::getPaymentList(); //支付方式列表
        $shippingList = ShippingModel::getShippingList(); //配送方式列表
        $this->assign('paymentList', $paymentList);
        $this->assign('shippingList', $shippingList);
        $this->display('order_query');
    }

    public function order_queryList()
    {
        $post = $_REQUEST;
        $orders_db = D('orders');
        if ($post['dosubmit']) {
            if ($post['ordernumber']) $where['order_sn'] = array('like', '%' . $post['ordernumber'] . '%');
            if ($post['email']) $where['delivery_email'] = array('like', '%' . $post['email'] . '%');
            if ($post['consignee']) $where['delivery_first_name'] = array('like', '%' . $post['consignee'] . '%');
            if ($post['postcode']) $where['delivery_postcode'] = array('like', '%' . $post['postcode'] . '%');
            if ($post['phone']) $where['delivery_phone'] = array('like', '%' . $post['phone'] . '%');
            if ($post['mobilephone']) $where['delivery_mobile'] = array('like', '%' . $post['mobilephone'] . '%');
            if ($post['province']) $where['delivery_province'] = array('like', '%' . $post['province'] . '%');
            if ($post['city']) $where['delivery_city'] = array('like', '%' . $post['city'] . '%');
            if ($post['address']) $where['delivery_address'] = array('like', '%' . $post['address'] . '%');
            if ($post['country']) $where['delivery_cid'] = array('eq', $post['country']);
            if ($post['shipping_method']) $where['shipping_method'] = array('eq', $post['shipping_method']);
            if ($post['payment_method']) $where['payment_method'] = array('eq', $post['payment_method']);
            if ($post['order_status']) $where['order_status'] = array('eq', $post['order_status']);
            if ($post['payment_status']) $where['payment_status'] = array('eq', $post['payment_status']);
            if ($post['shipping_status']) $where['shipping_status'] = array('eq', $post['shipping_status']);
            if ($post['start_time'] && $post['end_time']) {
                $where .= 'start_time >"' . strtotime($post['start_time']) . '" and start_time <= "' . strtotime($post['end_time']) . '"';
            }
        }

        //分页
        $pageRows = 10;
        $orders_db->where($where);
        $count = $orders_db->count();//总记录数
        import("ORG.Util.Page");// 导入分页类
        $Page = new Page($count, $pageRows);// 实例化分页类 传入总记录数和每页显示的记录数
        $pageShow = $Page->show();// 分页显示输出
        $this->assign('pageShow', $pageShow);

        $orders_db->limit($Page->firstRow . ',' . $Page->listRows);
        $orders_info = $orders_db->where($where)->select();
        //echo $orders_db->getLastSql();exit;
        $this->assign('ordersInfo', $orders_info);
        $this->assign('pageShow', $pageShow);
        $this->display('order_queryList');
    }

    /*设置身型数据*/
    public function set_measure()
    {

        //身型绑定的数据
        $m_data = C('m_data');

        if ($this->_POST('dosubmit')) {
            //echo "<pre />";
            // print_r($_POST);
            // exit;
            //order_item_id
            $order_item_id = $this->_POST('order_item_id');
            $measure_id = $this->_POST('measure_id');
            $product_model_id = $this->_POST('product_model_id');

            $size_measure = $_POST['size_measure'];
            $mtmadd_k = $_POST['mtmadd_k'];
            $mtmadd_v = $_POST['mtmadd_v'];

            //处理MTM变更的数据
            foreach ($mtmadd_k as $key => $val) {
                $size_measure[$key]['mtmadd'] = array();
                foreach ($val as $k => $v) {
                    if (!empty($v)) {
                        $size_measure[$key]['mtmadd'][$v] = $mtmadd_v[$key][$k];
                    }
                }
            }
            //print_r($size_measure);
            //保存默认数据
            OrderModel::set_size_measure($measure_id, 0, $size_measure);

            //保存本次订单需要的数据
            //确定服装类型
            if (!isset($m_data[$product_model_id])) {
                echo "类别参数错误，请联系技术";
            };
            //删除不需要的数据
            // foreach ($size_measure as $key => $val){
            // 	if(!in_array($key, $m_data[$product_model_id])){
            // 		unset($size_measure[$key]);
            // 	}
            // }
            //print_r($size_measure);
            OrderModel::set_size_measure(0, $order_item_id, $size_measure);

            //添加订单日志-------------
            //订单信息  
            $orderfigure = OrderModel::orderPrintFigure($order_item_id);
            //设置保存身型记录后改变订单状态
            $isSet = D('orders_log')->where(array('order_id' => $orderfigure['order_id'],'shipping_status' => '99'))->find();
            if(!$isSet){
                $orderInfo = D('orders')->where(array('id' => $orderfigure['order_id']))->find();
                $logData = array(
                    'order_id' => $orderInfo['id'],
                    'order_status' => $orderInfo['order_status'],
                    'payment_status' => $orderInfo['payment_status'],
                    'shipping_status' => '99',
                    'action_notice' => '设置保存身型记录',
                );
                OrderModel::insertOrdersLog($logData);
            }

            echo '<script stype="text/javascript" >window.opener=null;window.close();</script>';
            exit;
        }

        $order_item_id = intval($_GET['order_item_id']);
        $order_items_db = D('orders_items');
        $order_item_info = $order_items_db->find($order_item_id);
        $this->assign('order', $order_item_info);

        //用户的身形数据
        $user_measure = D('user_measure');
        $measure = $user_measure->where(array('id' => $order_item_info['measure_id']))->find();
        $this->assign('measure', $measure);
        //商品类型
        $orderfigure = OrderModel::orderPrintFigure($order_item_id);
        $this->assign('orderfigure', $orderfigure);
        //var_dump($orderfigure);

        //订单号
        $order_sn = D('orders')->where(array('id' => $orderfigure['order_id']))->getField('order_sn');
        $this->assign('order_id', $orderfigure['order_id']);
        $this->assign('order_sn', $order_sn);
        $this->assign('order_item_id', $order_item_id);

        //获取服装类型
        $product_model_id = D('product')
            ->where(array('id' => $order_item_info['product_id']))
            ->getField('model_id');
        //特俗礼服处理
        if ($product_model_id == 23) {
            $catid = D('product')
                ->where(array('id' => $order_item_info['product_id']))
                ->getField('catid');
            $parentid = D('category')
                ->where(array('id' => $catid))
                ->getField('parentid');
            if ($parentid > 0) $catid = $parentid;
            if ($catid == 2093) $product_model_id = 232;
            if ($catid == 2061) $product_model_id = 233;
        }
        if (!isset($m_data[$product_model_id])) {
            echo "类别参数错误，请联系技术";
        };
        $this->assign('product_model_id', $product_model_id);

        //合体 修身
        $model = preg_match('/:修身 /', $orderfigure['attr']) ? 2 : 1;

        //取配置项里的类别
        $size_type_arr = $size_type = C('size_type');
        //取此身型原先有得数据
        $size_measure_data = D('size_measure')
            ->field('data,time')
            ->where(array('measure_id' => $order_item_info['measure_id']))
            ->find();
        $size_measure = unserialize($size_measure_data['data']);
        //print_r('<pre />');
        //当是新数据和选尺码购物情况下 
        if (!$size_measure && $measure['m_status'] == 5) {
            $msizedata = unserialize($measure['measure_data']);
            foreach ($msizedata as $key => $val) {
                $size_data_notm_res = M('size_data_notm')->field('size_name_id,size_cm')
                    ->where(array('size' => $val, 'size_type' => $key))->select();
                $notm_arr = array();
                foreach ($size_data_notm_res as $notmval) {
                    $notm_arr[$notmval['size_name_id']] = $notmval['size_cm'];
                }
                $size_measure[$key] = array(
                    'model' => $model == 1 ? '合体' : '修身',
                    'chima' => '',
                    'cy' => $notm_arr,
                    'mtm' => $notm_arr,
                    'mtmadd' => '',
                );
            }

            $this->assign('is_xcm', 1);
        }

        //print_r($size_measure);exit;

        //获取修改身型的记录
        if ($size_measure_data) {
            $size_edit_measure_time = $size_measure_data['time'];
        } else {
            //下单时间
            $size_edit_measure_time = D('orders')->where(array('id' => $orderfigure['order_id']))->getField('start_time');
        }
        $size_edit_measure = D('size_edit_measure')->where(array('measure_id' => $order_item_info['measure_id'], 'edit_time' => array('egt', $size_edit_measure_time)))->order('id desc')->select();

        $eidt_array = array(); //修改数据的样式数组
        $eidt_array = array(NULL, NULL, NULL, NULL, NULL);//修改数据的样式数组

        foreach ($size_type as $key => $val) {
            $eidt_array[] = NULL; //修改数据的样式数组 
            $eidt_array[] = 'timeData'; //修改数据的样式数组
            $eidt_array[] = 'button'; //修改数据的样式数组

            $size_name = D('size_name')
                ->where(array('size_type' => $val['id'], 'display' => 0))
                ->order('sort asc')
                ->select();

            foreach ($size_name as $k => $v) {
                //more_type为0的是尺码名称，如果有保存的数据则取保存的数据出来
                if ($v['more_type'] == 0) {
                    if ($size_measure[$val['id']]['cy']) {
                        $v['cysize'] = $size_measure[$val['id']]['cy'][$v['id']] + MeasureModel::user_measure_val_edit($size_edit_measure, $v['field_name']);
                    } else {
                        if (!empty($v['field_name']) && isset($measure[$v['field_name']])) {
                            //如果原先没有保存的数据情况下，根据身型调取相应的合体 修身增加值
                            $addsize = ($model == 2 && in_array($val['id'], $m_data[$product_model_id])) ? $v['slim_add'] : $v['fit_add'];
                            $v['cysize'] = $measure[$v['field_name']] + $addsize;
                        }
                    }
                    if ($size_measure[$val['id']]['mtm']) {
                        $v['mtmsize'] = $size_measure[$val['id']]['mtm'][$v['id']];
                    }

                    $eidt_array[] = $v['field_name']; //修改数据的样式数组  
                }
                $size_name[$k] = $v;

            }
            $size_type[$key]['size_name'] = $size_name;

            $eidt_array[] = NULL; //修改数据的样式数组
            $eidt_array[] = 'button'; //修改数据的样式数组
            $eidt_array[] = 'button'; //修改数据的样式数组
            $eidt_array[] = 'button'; //修改数据的样式数组
            $eidt_array[] = 'button'; //修改数据的样式数组
            $eidt_array[] = 'button'; //修改数据的样式数组

            //取MTM变更数据
            if ($size_measure[$val['id']]['mtmadd']) {
                $size_type[$key]['mtmselect'] = $size_measure[$val['id']]['mtmadd'];
            }
            //取身型
            $size_type[$key]['model_val'] = in_array($val['id'], $m_data[$product_model_id]) ? $model : 0;
            if ($size_measure[$val['id']]['model'])
                $size_type[$key]['model'] = $size_measure[$val['id']]['model'];
            //取尺码
            if ($size_measure[$val['id']]['chima'])
                $size_type[$key]['chima'] = $size_measure[$val['id']]['chima'];

            //取尺码
            if ($size_measure_data['time'])
                $size_type[$key]['time'] = $size_measure_data['time'];
        }

        $this->assign('size_type', $size_type);
        $this->assign('size_measure', $size_measure);

        //查询用户修改数据 成数组形势
        $eidt_array_data = array();
        $size_name = D('size_name')
            ->where(array('display' => 0, 'more_type' => 0))
            ->order('sort asc')
            ->select();
        foreach ($eidt_array as $k => $v) {
            $is_get_ok = false;
            foreach ($size_name as $key => $val) {
                if ($v && $val['field_name'] == $v) {
                    $eidt_data[$k]['name'] = $v;
                    $eidt_data[$k]['value'] = $val['size_name'];
                    $is_get_ok = true;
                    continue;
                }
            }
            if (!$is_get_ok) {
                $eidt_data[$k]['name'] = $v;
                $eidt_data[$k]['value'] = '';
            }
        }
        $eidt_array_data[] = $eidt_data;
        //echo "<pre />";print_r($size_name);exit;

        foreach ($size_edit_measure as $key => $val) {
            $val['data'] = unserialize($val['data']);
            foreach ($eidt_array as $k => $v) {
                //print_r($v);echo "<br />";
                if (isset($val['data'][$v])) {
                    $eidt_data[$k]['name'] = $v;
                    $eidt_data[$k]['value'] = $val['data'][$v];
                } else if ($v == 'timeData') {
                    $eidt_data[$k]['name'] = $v;
                    $eidt_data[$k]['value'] = date('md H:i', $val['edit_time']);
                    if ($val['type'] == 0) $eidt_data[$k]['value'] = '' . $eidt_data[$k]['value'];
                } else {
                    $eidt_data[$k]['name'] = $v;
                    $eidt_data[$k]['value'] = '';
                }
            }
            $eidt_array_data[] = $eidt_data;
        }
        $this->assign('eidt_array_data', $eidt_array_data);
        //echo "<pre />";print_r($eidt_array_data);

        //获取身型字段
        $measure_field = MeasureModel::user_measure_field();
        $this->assign('measure_field', $measure_field);

        //查询size_data  根据相应需求存json，给页面的js调用
        foreach ($size_type_arr as $key => $val) {

            //以尺码方式存数据
            $sql = "select * from size_data where  size_name_id in(select id 
            	from size_name where more_type=0 and size_type=" . $val['id'] . ") order by size asc";
            $size_data = M()->query($sql);
            $size_data_res = array();
            foreach ($size_data as $k => $v) {
                $size_data_res[$v['size']][] = array(
                    'size_name_id' => $v['size_name_id'],
                    'size_cm' => $v['size_cm'],
                );
            }
            $size_type_data[$val['id']] = $size_data_res;

            //取胸围臀围数据（页面自动变化值）
            $size_name_change_id = D('size_name')
                ->where(array('size_type' => $val['id'], 'is_change' => 1, 'more_type' => 0, 'display' => 0))
                ->order('sort asc')
                ->getField('id');
            $change_data = D('size_data')
                ->where(array('size_name_id' => $size_name_change_id))
                ->select();
            $change_data_res = array();
            foreach ($change_data as $k => $v) {
                $change_data_res[$v['size_cm']] = $v['size'];
            }
            $size_change_data[$size_name_change_id] = $change_data_res;
        }
        //九分裤 短裤 牛仔裤 的数据跟长裤
        $size_change_data[121]=$size_change_data[108] = $size_change_data[95] = $size_change_data[16];
        foreach ($size_type_data[3] as $key => $size_data_res) {
            $avalRes = array();
            $bvalRes = array();
            $jeansRes= array();
            foreach ($size_data_res as $val) {
                if ($val['size_name_id'] == 14) {
                    $aval['size_name_id'] = 93;
                    $bval['size_name_id'] = 106;
                    $jeans['size_name_id'] = 119;
                } else if ($val['size_name_id'] == 15) {
                    $aval['size_name_id'] = 94;
                    $bval['size_name_id'] = 107;
                    $jeans['size_name_id'] = 120;
                } else if ($val['size_name_id'] == 16) {
                    $aval['size_name_id'] = 95;
                    $bval['size_name_id'] = 108;
                    $jeans['size_name_id'] = 121;
                } else if ($val['size_name_id'] == 17) {
                    $aval['size_name_id'] = 96;
                    $bval['size_name_id'] = 109;
                    $jeans['size_name_id'] = 122;
                } else if ($val['size_name_id'] == 18) {
                    $aval['size_name_id'] = 97;
                    $bval['size_name_id'] = 110;
                    $jeans['size_name_id'] = 123;
                } else if ($val['size_name_id'] == 19) {
                    $aval['size_name_id'] = 98;
                    $bval['size_name_id'] = 111;
                    $jeans['size_name_id'] = 124;
                }else if ($val['size_name_id'] == 20) {

                    $jeans['size_name_id'] = 125;
                }
                $aval['size_cm'] = $val['size_cm'];
                $bval['size_cm'] = $val['size_cm'];
                $jeans['size_cm']=$val['size_cm'];
                $avalRes[] = $aval;
                $bvalRes[] = $bval;
                $jeansRes[]=$jeans;
            }
            $size_type_data[6][$key] = $avalRes;
            $size_type_data[7][$key] = $bvalRes;
            $size_type_data[8][$key] =$jeansRes;
        }
        //所有大衣
        $size_change_data[151] = $size_change_data[174]=$size_change_data[33];
        foreach ($size_type_data[5] as $key => $size_data_res) {
            $coatRes = array();
            $coatRes2 = array();
            foreach ($size_data_res as $val) {
                if ($val['size_name_id'] == 32) {
                    $coat['size_name_id'] = 150;
                    $coat2['size_name_id'] = 173;
                    $coat['size_cm'] = $val['size_cm']-4;
                    $coat['size_cm'] = $val['size_cm']+4;
                } else if ($val['size_name_id'] == 33) {
                    $coat['size_name_id'] = 151;
                    $coat2['size_name_id'] = 174;
                } else if ($val['size_name_id'] == 34) {
                    $coat['size_name_id'] = 152;
                    $coat2['size_name_id'] = 175;
                } else if ($val['size_name_id'] ==35) {
                    $coat['size_name_id'] = 153;
                    $coat2['size_name_id'] = 176;
                } else if ($val['size_name_id'] == 36) {
                    $coat['size_name_id'] = 154;
                    $coat2['size_name_id'] = 177;
                } else if ($val['size_name_id'] == 37) {
                    $coat['size_name_id'] = 155;
                    $coat2['size_name_id'] = 178;
                }else if ($val['size_name_id'] == 38) {
                    $coat['size_name_id'] = 156;
                    $coat2['size_name_id'] = 179;
                }
                else if ($val['size_name_id'] == 39) {
                    $coat['size_name_id'] = 157;
                    $coat2['size_name_id'] = 180;
                }
                else if ($val['size_name_id'] == 40) {
                    $coat['size_name_id'] = 158;
                    $coat2['size_name_id'] = 181;
                }
                $coat['size_cm'] = $val['size_cm'];
                $coat2['size_cm'] = $val['size_cm'];
                if ($val['size_name_id'] == 32) {
                    $coat['size_cm'] = $val['size_cm']-4;
                    $coat2['size_cm'] = $val['size_cm']+4;
                }
                $coatRes[] = $coat;
                $coatRes2[] = $coat2;

            }
            $size_type_data[9][$key] = $coatRes;
            $size_type_data[10][$key] = $coatRes2;

        }
        $this->assign('size_change_data', $size_change_data);
        $this->assign('size_type_data', $size_type_data);

        $this->display('set_measure');

    }

    //查找当前身形用户的历史订单
    public function order_list_by_measure($user_id, $order_id)
    {   
        $userInfo = UserModel::getUserInfo($user_id);
        $user_id = $userInfo['is_partner'] == 0 ? $user_id : 0;
        if ($user_id) {
            $order_list = M('orders')->where("user_id=$user_id")->order('id desc')->select();
            if ($ghost_list) {
                $order_list[] = $order_list;
            }
            $user_email = M('users')->where('id=' . $user_id)->getField('email');
            $ghost_list = M('orders')->where(" user_id=0 and delivery_email='" . $user_email . "'")->select();//游客购买并且使用与当前用户相同的邮箱地址 也加入相关订单
            if ($ghost_list)
                $order_list = array_merge($order_list, $ghost_list);

            if (count($order_list) > 1) {
                foreach ($order_list as $k => $v) {
                    if ($order_id == $v['id']) {
                        continue;
                    }
                    $order_list_1[$k]['order_info'] = $v;
                    $order_info_list = M('orders_items')->where("order_id={$v['id']}")->select();
                    foreach ($order_info_list as $kk => $vv) {
                        $data = array();
                        //var_dump($vv);
                        $data['product_info'] = M('product_items')->field('name,product_id')->where("product_id={$vv['product_id']} and language_id=6")->find();
                        if (!$data['product_info']['name']) {
                            $data['product_info'] = M('product_items')->field('name,product_id')->where("product_id={$vv['product_id']} and language_id=1")->find();
                        }
                        $data['measure_name'] = M('user_measure')->field('measure_name')->where("id={$vv['measure_id']}")->find();
                        if ($kk == 0) {
                            $order_list_1[$k]['order_info']['product_info'] = $data;
                            continue;
                        }
                        $order_list_1[$k]['list'][] = $data;
                    }
                    $order_list_1[$k]['delivery_status'] = M('orders_delivery')->where('order_id=' . $v['id'])->find();
                }

                $this->assign('order_list', $order_list_1);
                $contents = $this->fetch('order_list_by_measure');
                if ($contents)
                    echo $contents;

            }
        }
    }

    //显示子订单数据
    public function order_zlist()
    {
        $order_id = intval($_GET['order_id']);

        //查询订单子数据
        $product = OrderModel::getOrderProductList($order_id); //订单产品列表
        foreach ($product as $k => $v) {
            $product[$k]['isset_size_measure'] = OrderModel::isset_size_measure(0, $v['id']);
            $product[$k]['inventory'] = D('inventory')->where(array('order_item_id' => $v['id']))->count();
        }
        //var_dump($product[0]['measure_data']);
        $this->assign('product', $product);

        $this->display('order_zlist');

    }

    public function ajax_read_order_zlist()
    {
        $order_id = intval($_GET['order_id']);
        echo file_get_contents('http://' . $_SERVER['HTTP_HOST'] . U('order/order_zlist', 'order_id=' . $order_id));
    }


    //订单暂停恢复
    public function order_pro()
    {
        $order_id = intval($_REQUEST['order_id']);
        $order_status = intval($_REQUEST['order_status']);
        $action_notice = $_REQUEST['action_notice'];
        $order_db = D('orders');
        $orderInfo = $order_db->field('id,payment_status,payment_status,shipping_status')->where('id=' . $order_id)->find();
        if (!$orderInfo) {
            echo "订单不存在!";
            exit;
        };
        $order_db->where('id=' . $order_id)->save(array('order_status' => $order_status, 'update_time' => time()));

        //添加订单日志
        $logData = array(
            'order_id' => $orderInfo['id'],
            'order_status' => $order_status,
            'payment_status' => $orderInfo['payment_status'],
            'shipping_status' => $orderInfo['shipping_status'],
            'action_notice' => $action_notice ? trim($action_notice) : null,
        );
        OrderModel::insertOrdersLog($logData);
        echo 1;
    }

    public function order_pro_show()
    {
        $order_id = intval($_REQUEST['order_id']);
        $order_db = D('orders');
        $order_status = $order_db->where('id=' . $order_id)->getField('order_status');
        if ($order_status == OrderModel::ORDER_PAUSE) {
            echo 'document.writeln("此订单已暂停")';
        } else {
            echo 'document.writeln("<input type=\"button\" value=\"暂停订单\" onclick=\"order_pro_tips(this, ' . $order_id . ');\" />")';
        }
    }

    public function order_log()
    {
        $order_id = intval($_REQUEST['order_id']);
        $order = OrderModel::getOrderInfo($order_id);
        $order['logs'] = OrderModel::getOrdersLogList($order_id); //订单日志
        $this->assign('order', $order);
        $this->display('order_log');
    }

    //订单统计及走势图
    public function order_count()
    {

        $post = $_REQUEST;

        $where = array();
        //搜索订单状态
        $order_status = 9999;
        if (isset($post['order_status']) && $post['order_status'] != 9999) {
            $where['orders.order_status'] = $post['order_status'];
            $order_status = $post['order_status'];
        }
        $this->assign('order_status', $order_status);
        //搜索支付状态
        $payment_status = 1;
        if (isset($post['payment_status']) && $post['payment_status'] != 9999) {
            $where['orders.payment_status'] = $post['payment_status'];
            $payment_status = $post['payment_status'];
        }
        if ($post['payment_status'] == 9999) $payment_status = 9999;
        $this->assign('payment_status', $payment_status);
        //搜索配送状态
        $shipping_status = 9999;
        if (isset($post['shipping_status']) && $post['shipping_status'] != 9999) {
            $where['orders.shipping_status'] = $post['shipping_status'];
            $shipping_status = $post['shipping_status'];
        }
        $this->assign('shipping_status', $shipping_status);

        //时间查询
        $this->assign('time_type', intval($post['time_type']));

        $time_type_val = (intval($post['time_type']) == 1) ? 'start_time' : 'payment_time';

        //如果时间为空，默认出前七天
        if (!$post['end_time']) {
            $end_time = time();
            $post['end_time'] = date('Y-m-d', $end_time);
        }
        if (!$post['start_time']) {
            $post['start_time'] = date('Y-m-d', (strtotime($post['end_time']) - 3600 * 24 * 7));
        }
        if ($post['start_time'] && $post['end_time']) {
            $start_time = strtotime($post['start_time']);
            $end_time = strtotime($post['end_time']);
            $where[$time_type_val] = array(array('egt', $start_time), array('lt', $end_time), 'and');
        }
        $this->assign('start_time', $post['start_time']);
        $this->assign('end_time', $post['end_time']);

        //日期
        $typeArr = array('year', 'month', 'week', 'day');
        $date_type = in_array($post['date_type'], $typeArr) ? $post['date_type'] : 'day';
        $this->assign('date_type', $date_type);

        $order_db = D('orders');

        if (!isset($post['order_status']) || $post['order_status'] != OrderModel::ORDER_DEL) {
            $where['_string'] = ' order_status !=' . OrderModel::ORDER_DEL;
        }

        $field = 'sum(pay_amount) as pay_amount, count(id) as order_num';

        $orderAllRes = array(
            'pay_amount' => 0,
            'order_num' => 0,
        );

        //图标数据
        $getDateArr = getAllDates($post['start_time'], $post['end_time'], $date_type);
        $orderOneRes = array();
        foreach ($getDateArr as $val) {
            if ($date_type == 'year') {
                $start_time = strtotime(date('Y-01-01 00:00:00', strtotime($val)));
                $end_time = strtotime(date('Y-12-31 23:59:59', strtotime($val)));
                $date_str = date('Y', $end_time);
            } else if ($date_type == 'month') {
                list($start_time, $end_time) = dateStage(date('Y', strtotime($val)), date('m', strtotime($val)));
                $date_str = date('Y-m', $end_time);
            } else if ($date_type == 'week') {
                $whatDay = date('w', strtotime($val));
                if ($whatDay == 0) $whatDay = 7;
                $start_time = strtotime($val) - ($whatDay - 1) * 3600 * 24;
                $start_time = strtotime(date('Y-m-d 00:00:00', $start_time));
                $end_time = strtotime($val) + (7 - $whatDay) * 3600 * 24;
                $end_time = strtotime(date('Y-m-d 23:59:59', $end_time));
                $date_str = date('m-d', $start_time) . '~' . date('m-d', $end_time);
            } else {
                $start_time = strtotime(date('Y-m-d 00:00:00', strtotime($val)));
                $end_time = strtotime(date('Y-m-d 23:59:59', strtotime($val)));
                $date_str = date('m-d', $end_time);
            }
            $where[$time_type_val] = array(array('egt', $start_time), array('lt', $end_time), 'and');

            $order_db->field($field);
            $order_db->where($where);
            $oneRes = $order_db->find();
            $pay_amount = $oneRes['pay_amount'] ? $oneRes['pay_amount'] : 0;
            $order_num = $oneRes['order_num'] ? $oneRes['order_num'] : 0;
            $orderOneRes[] = array(
                'pay_amount' => $pay_amount,
                'order_num' => $order_num,
                'labels' => $date_str,
            );
            $orderAllRes['pay_amount'] += $pay_amount;
            $orderAllRes['order_num'] += $order_num;
        }

        $this->assign('orderAllRes', $orderAllRes);
        $this->assign('orderOneRes', $orderOneRes);
        $this->display('order_count');
    }

    public function beach_select_edit()
    {
        $order_ids = implode(',', $_POST['oids']);

        $order_db = M('orders');
        $order_item = M('orders_items');
        $product_item = M('product_items');
        $product_db = M('product');

        $order_list = $order_db->field('id,order_sn,shipping_method,order_amount,pay_amount,delivery_country,payment_time,payment_status,shipping_time,delivery_email,delivery_first_name,delivery_last_name')->where("id IN($order_ids)")->order('id desc')->select();

        if (isset($_POST['product'])) {//商品清单
            $i = 1;
            $j = 1;
            $m = 1;
            foreach ($order_list as $k => $v) {
                $item_info = $order_item->where('order_id=' . $v['id'])->select();
                foreach ($item_info as $kk => $vv) {
                    $data = array();
                    $time = '';
                    $time_1 = '';
                    $data = array(
                        // 'paytime' => $time,
                        'order_sn' => $v['order_sn'] . '-' . $vv['id'],
                    );
                    $product = $product_item->field('product_items.name,product.*,category.parentid')->join('left join product on product_items.product_id=product.id')
                        ->join('left join category on category.id=product.catid')->where('product_items.language_id=6 and product_items.product_id=' . $vv['product_id'])->find();
                    if (!$product) {
                        $product = $product_item->field('product_items.name,product.*,category.parentid')->join('left join product on product_items.product_id=product.id')
                            ->join('left join category on category.id=product.catid')->where('product_items.language_id=1 and product_items.product_id=' . $vv['product_id'])->find();
                    }
                    $size_measure_info = M('size_measure')->field('time')->where('order_item_id=' . $vv['id'] . ' and measure_id=0')->find();
                    if ($size_measure_info['time'] != 0) {
                        $time = date('Y-m-d', $size_measure_info['time']);
                        $time_1 = date('Y-m-d', $size_measure_info['time'] + 950400);
                    } else {
                        $time = '';
                    }
                    if (in_array($product['parentid'], array(2093, 2061, 2104))) {//西装
                        $data = array(
                            // 'paytime' => $time,
                            'id' => $i++,
                            'order_sn' => $v['id'] . '-' . $vv['id'],
//                        'name' => $product['name'],
                        );
                        if ($product['parentid'] == 2093) {
                            $data['num1'] = $vv['qty'];
                            $data['num2'] = $vv['qty'] + $vv['pants_qty'];
                            $data['num3'] = '';
                        } else if ($product['parentid'] == 2061) {
                            $data['num1'] = $vv['qty'];
                            $data['num2'] = $vv['qty'] + $vv['pants_qty'];
                            $data['num3'] = $vv['qty'];
                        } else if ($product['parentid'] == 2104) {
                            $data['num1'] = $vv['qty'];
                            $data['num2'] = '';
                            $data['num3'] = '';
                        }
                        $data['time'] = $time;//生产时间
                        $data['time_2'] = $time_1;
                        $suit_data[] = $data;
                    }
                    if ($product['parentid'] == 2062) {//衬衫
                        $data = array(
                            // 'paytime' => $time,
                            'id' => $j++,
                            'order_sn' => $v['id'] . '-' . $vv['id'],
                            'shirt_qty' => $vv['qty'],
                            'time' => $time,//生产时间
                            'time_2' => $time_1,
                        );
                        $shirt_data[] = $data;
                    }

                    if ($product['catid'] == 2066) {//大衣
                        $data = array(
                            // 'paytime' => $time,
                            'id' => $m++,
                            'order_sn' => $v['id'] . '-' . $vv['id'],
                        );
                        if (in_array($vv['product_id'], array(651, 652, 653, 654))) {
                            $data['fengyi'] = 1;
                            $data['dayi'] = '';
                        } else {
                            $data['fengyi'] = '';
                            $data['dayi'] = 1;
                        }
                        $data['time'] = $time;//生产时间
                        $data['time_2'] = $time_1;
                        $coat_data[] = $data;
                    }

                }
            }
            import('COM.XmlExcel');
            $excel = new XmlExcel;
            $excel->setDefaultAlign('Center');
            if ($suit_data) {
                $excel_title = array('序号', '订单号', '上衣', '裤子', '马甲', '安排生产时间', '预计寄回时间', '备注');
                $excel->setSheetHead($excel_title, '西服');
                $excel->addRows($suit_data, '西服');
            }
            if ($shirt_data) {
                $excel_title = array('序号', '订单号', '衬衫数量', '安排生产时间', '预计寄回时间', '备注');
                $excel->setSheetHead($excel_title, '衬衫');
                $excel->addRows($shirt_data, '衬衫');
            }

            if ($coat_data) {
                $excel_title = array('序号', '订单号', '风衣', '大衣', '安排生产时间', '预计寄回时间', '备注');
                $excel->setSheetHead($excel_title, '风衣和大衣');
                $excel->addRows($coat_data, '风衣和大衣');
            }
            $excel->setDefaultWidth(100);
            $excel->export('商品清单');
        } else if (isset($_POST['logistics'])) {//发货单
            $logistics_data = array();
            foreach ($order_list as $k => $v) {
                $data = array();
                $data = array(
                    'id' => $k + 1,
                    'shipping_time' => $time,
                    'shipping_method' => $v['shipping_method'],
                );
                $info = M('orders_delivery')->where('order_id=' . $v['id'])->find();
                $data['shipping_no'] = $info['shipping_no'];
                $logistics_data[] = $data;
            }
            import('COM.XmlExcel');
            $excel = new XmlExcel;
            $excel_title = array('序号', '发货时间', '物流方式', '运单号', '送达类型', '重量', '金额', '备注');
            $excel->setSheetHead($excel_title, '物流');
            $excel->addRows($logistics_data, '物流');
            $excel->setDefaultWidth(100);
            $excel->export('物流清单');
        } else if (isset($_POST['pack'])) {//包装发货清单
            $pack_arr = array();
            foreach ($order_list as $k => $v) {
                $item_info = $order_item->where('order_id=' . $v['id'])->select();
                $data = array();
                $product_names = array();
                $product = array();
                $time_arr = array();
                $time_all = array();
                $time = '';
                $time_2 = '';
                foreach ($item_info as $kk => $vv) {
                    $product = $product_item->field('product_items.name,product.*,category.parentid')->join('left join product on product_items.product_id=product.id')
                        ->join('left join category on category.id=product.catid')->where('product_items.language_id=6 and product_items.product_id=' . $vv['product_id'])->find();
                    if (!$product) {
                        $product = $product_item->field('product_items.name,product.*,category.parentid')->join('left join product on product_items.product_id=product.id')
                            ->join('left join category on category.id=product.catid')->where('product_items.language_id=1 and product_items.product_id=' . $vv['product_id'])->find();

                    }
                    $product_names[] = $product['name'];
                    $size_measure_info = M('size_measure')->field('time')->where('order_item_id=' . $vv['id'] . ' and measure_id=0')->find();
                    if ($size_measure_info)
                        $time_arr[] = $size_measure_info['time'];
                }
                $m_time = '';
                if ($time_arr[0]) {
                    for ($i = 0; $i < count($time_arr); $i++) {
                        if ($time_arr[$i] > $time_arr[$i + 1]) {
                            $m_time = $time_arr[$i];
                        }
                    }
                    $time = date('Y-m-d', $m_time);
                    $time_2 = date('Y-m-d', $m_time + 1296000);
                } else {
                    $time = '';
                    $time_2 = '';
                }
                $data = array(
                    'id' => $k + 1,
                    'order_sn' => $v['id'],
                    'shengchanshijian' => $time,
                    'fahuoshijian' => $time_2,
                    'name' => implode(',', $product_names),
                    'delivery_country' => $v['delivery_country'],
                );


                $pack_arr[] = $data;
            }
            import('COM.XmlExcel');
            $excel = new XmlExcel;
            $excel_title = array('序号', '订单号', '安排生产时间', '预计发货时间', '购买商品', '订单来源');
            $excel->setSheetHead($excel_title, '包装发货');
            $excel->addRows($pack_arr, '包装发货');
            $excel->setDefaultWidth(100);
            $excel->export('包装发货清单');
        } else if (isset($_POST['tuishui']) || isset($_POST['tuishui_test'])) {//退税单
            $tuishui_test = isset($_POST['tuishui_test']) ? true : false;
            $order_list = $order_db->where("id IN($order_ids) and shipping_status=1")->order('id desc')->select();
            if (!$order_list) {
                echo "数据为空,请选择已发货订单!";
                exit;
            }
            //报文配置数据
            $settlementConfig = $this->settlementConfig();
            $config = $settlementConfig['config'];
            $product_config = $settlementConfig['product_config'];
//            $where['payment_status'] = 1;
//            $where['shipping_status'] = 1;//已发货订单
//            $order_list = M('orders')->where($where)->order('id desc')->select();
            $shipping_list = M('shipping')->select();
            foreach ($shipping_list as $k => $v) {
                $shipping[$v['id']] = $v['name'];
            }
            //var_dump($shipping);die;
            $excel_title = array('订单号', '货号', '编号', '中文品名', '单位', '海关法定单位代码', '数量', '重量', '单价', '币种',  '金额', '国家', '物流', '运单号', '发货日期', '发件人', '签收人', '省', '市', '地址', '地址2');
            foreach ($excel_title as $key => $val) {
                $excel_title_gbk[] = iconv('utf-8', 'gbk', $val);
            }
            $ext_arr = array();

            foreach ($order_list as $k => $v) {
                $item_list = M('orders_items')->field('orders_items.*,product.*,orders_items.id as orders_items_id')->join('left join product on orders_items.product_id=product.id')->where('orders_items.order_id=' . $v['id'])->select();
                //var_dump($item_list);die;

                if ($item_list) {
                    foreach ($item_list as $kk => $vv) {
                        //var_dump($vv);die;
                        $pinming = '';
                        $pinmingEn = '';
                        $haiguancode = '';
                        $weight = '';
                        if ($product_config[$vv['product_id']]) {
                            $pinming = $product_config[$vv['product_id']]['pinming'];
                            $pinmingEn = $product_config[$vv['product_id']]['pinmingEn'];
                            $haiguancode = $product_config[$vv['product_id']]['haiguancode'];
                            $weight = $product_config[$vv['product_id']]['weight'];
                        } else if ($config[$vv['catid']]) {
                            $pinming = $config[$vv['catid']]['pinming'];
                            $pinmingEn = $config[$vv['catid']]['pinmingEn'];
                            $haiguancode = $config[$vv['catid']]['haiguancode'];
                            $weight = $config[$vv['catid']]['weight'];
                        }
                        $product = D('product')->where(array('id' => $vv['product_id']))->find();
                        $data = array(
                            $v['order_sn'] . '-' . $vv['orders_items_id'],
                            $product['sn'],
                            $haiguancode,
                            $pinming,
                            '千克',
                            '',
                            $vv['qty'],
                            $vv['qty'] * $weight,              
                            (int)$vv['advanced_price'] != 0 ? $vv['advanced_price'] : $vv['custom_price'],
                            $v['currency'] ? $v['currency'] : 'USD', 
                            ((int)$vv['advanced_price'] != 0 ? $vv['advanced_price'] : $vv['custom_price']) * $vv['qty'],//
                            $v['delivery_country'],
                            'fedex',//$shipping[$v['shipping_id']],
                            $v['shipping_no'],
                            $v['shipping_time'] ? date('Ymd', $v['shipping_time']) : '',
                            'ownonly',
                            $v['delivery_first_name'] . ' ' . $v['delivery_last_name'],
                            $v['delivery_province'],
                            $v['delivery_city'],
                            $v['delivery_address'] . ' ' . $v['delivery_address2'],
                            '',
                        );
                        $ext_arr[] = $data;
                        $data = array();
                    }
                }

            }
            foreach ($ext_arr as $ext_arr_one) {
                $ext_arr_gbk_one = array();
                foreach ($ext_arr_one as $key => $val) {
                    $ext_arr_gbk_one[] = iconv('utf-8', 'gbk', trim($val));
                }
                $ext_arr_gbk[] = $ext_arr_gbk_one;
            }
            $ext_arr = array();
            $ext_arr = $ext_arr_gbk;

            //联邦数据带标题
            $ext_arr_fedex[] = $excel_title_gbk;
            foreach ($ext_arr as $ext_arr_one) {
                $ext_arr_one[2] = "\t" . $ext_arr_one[2];
                $ext_arr_one[14] = "\t" . $ext_arr_one[14];
                $ext_arr_fedex[] = $ext_arr_one;
            }

            //针对ftp文件名命名规则为GPXXXyyyymmdd999.CSV，
            //其中GP为固定前缀，XXX是三位英文，由你们定，可以定多组，
            //但必须提前通知我们准备，否则无法识别，
            //yyyymmdd为日期，999为序号，每天都从001开始，必须连号。
            $serialnoWhere['_string'] = 'addtime >= ' . strtotime(date('Y-m-d 00:00:00')) . '  and addtime <= ' . strtotime(date('Y-m-d 23:59:59'));
            $serialNo = D('serialno')->where($serialnoWhere)->count();
            $serialNo += 1;
            $serialNo = $serialNo < 10 ? '00' . $serialNo : ($serialNo < 100 ? '0' . $serialNo : $serialNo);
            $file_name = 'GPOWN' . date('Ymd', time()) . $serialNo . '.csv';
            // -----------导出excel----------                
            //header("Content-type: application/vnd.ms-excel". 'GB2312');
            //header("Content-Disposition: attachment; filename=".$file_name);
            //header("Pragma: no-cache");
            //header("Expires: 0");
            //echo $header. $data;
            $path = dirname(__FILE__) . '/tuishui';
            if (!is_dir($path)) {
                mkdir($path);
            }

            $file_name_path = $path . '/' . $file_name;
            file_put_contents($file_name_path, '');

            $file_name_path_fedex = $path . '/fedex_' . $file_name;
            file_put_contents($file_name_path_fedex, '');


            function writeCsvToFile($file, array $filedata)
            {
                $fp = fopen($file, 'w');

                //Windows下使用BOM来标记文本文件的编码方式  
                //fwrite($fp,'\xEF\xBB\xBF');  
                foreach ($filedata as $line) {
                    fputcsv($fp, $line);
                }

                fclose($fp);
            }

            //给电子口岸
            writeCsvToFile($file_name_path, $ext_arr);
            //给联邦				
            writeCsvToFile($file_name_path_fedex, $ext_arr_fedex);

            $success = false;
            if (file_exists($file_name_path)) {
                $success = true;
                //-----------上传到融易通---------- 测试前跟丁工说一声
                if($tuishui_test){
                    $user_name = "khitest"; //测试账号
                    $password = "3mozbh@0216";
                }else{
                    $user_name = "gupin"; //正式账号
                    $password = "a5nnh2@0525";
                }
                $host = "60.191.126.171";//测试ftp
                $port = 21;
                $ftp_connect = ftp_connect($host, $port);//上传至融易通
                $ftp_result = ftp_login($ftp_connect, $user_name, $password);
                ftp_pasv($ftp_connect, true);//开启被动模式 
                if (ftp_put($ftp_connect, $file_name, $file_name_path, FTP_ASCII)) {
                    $str = "上传文件成功";
                    if(!$tuishui_test){
                        //修改订单退税状态
                        foreach ($order_list as $k => $v) {
                            D('orders')->where(array('id' => $v['id']))->save(array('is_drawback' => 1));
                        }
                        //保存记录 统计数量
                        D('serialno')->add(array('addtime' => time(), 'name' => $file_name));
                    }else{
                        $str .= '(测试)';
                    }
                } else {
                    $str = "上传文件失败!请下载文件后,联系技术上传!";
                }
                ftp_close($ftp_connect);
                //unlink($file_name_path); //删除csv文件
                //$file_name = iconv( 'GB2312', 'utf-8', $file_name); 
                $str .= ' - ' . $file_name;
            } else {
                $str = "生成文件失败";
            }
            //echo "<script>alert('".$file_name."');history.back();</script>";
            echo $str . '<br />';
            if ($success){
                echo '<a href="/admin/Lib/Action/tuishui/' . $file_name . '">点此下载(电子口岸)</a>';
                echo '--------<br /><br /><br /><br />';
                echo '<a href="/admin/Lib/Action/tuishui/' . 'fedex_' . $file_name . '">点此下载(联邦快递)</a>';
            }
            exit;
        } else if (isset($_POST['printMeasure'])) {//包装发货清单
            $pack_arr = array();
            foreach ($order_list as $k => $v) {
                $order_data = array();
                $item_info = $order_item->where('order_id=' . $v['id'])->select();
                foreach ($item_info as $kk => $vv) {
                    $mid = intval($vv['measure_id']);
                    if ($mid > 0) {
                        //面料列表
                        $suppliers_id = D('product')->where(array('id' => $vv['product_id']))
                            ->getField('suppliers_id');
                        $suppliers_name = D('suppliers')->where(array('suppliers_id' => $suppliers_id))
                            ->getField('suppliers_name');
                        //如果此订单已经有了此身型的数据就跳出
                        if (isset($order_data[$mid]) && $order_data[$mid]) {
                            $order_data[$mid]['31'] = $order_data[$mid]['31'] . ' ' . $suppliers_name;
                            continue;
                        }
                        $measure = MeasureModel::get_measure_info($mid);
                        if (!$measure) continue;
                        if ($measure['shoulder'] == 1) {
                            $shoulder = "方肩";
                        } elseif ($measure['shoulder'] == 2) {
                            $shoulder = "介于高和正常";
                        } elseif ($measure['shoulder'] == 3) {
                            $shoulder = "正常";
                        } elseif ($measure['shoulder'] == 4) {
                            $shoulder = "介于正常和溜肩";
                        } elseif ($measure['shoulder'] == 5) {
                            $shoulder = "溜肩";
                        } else {
                            $shoulder = '正常';
                        }
                        if ($measure['chest_type'] == 1) {
                            $chest_type = "胸肌发达";
                        } elseif ($measure['chest_type'] == 2) {
                            $chest_type = "介于发达和正常";
                        } elseif ($measure['chest_type'] == 3) {
                            $chest_type = "正常";
                        } elseif ($measure['chest_type'] == 4) {
                            $chest_type = "介于正常和肥胖";
                        } elseif ($measure['chest_type'] == 5) {
                            $chest_type = "厚胸";
                        } else {
                            $chest_type = '正常';
                        }
                        if ($measure['stomach_type'] == 1) {
                            $stomach_type = "平肚";
                        } elseif ($measure['stomach_type'] == 2) {
                            $stomach_type = "介于平腹和微凸";
                        } elseif ($measure['stomach_type'] == 3) {
                            $stomach_type = "正常";
                        } elseif ($measure['stomach_type'] == 4) {
                            $stomach_type = "介于微凸和凸腹";
                        } elseif ($measure['stomach_type'] == 5) {
                            $stomach_type = "凸肚";
                        } else {
                            $stomach_type = '正常';
                        }
                        if ($measure['posture'] == 1) {
                            $posture = "平背";
                        } elseif ($measure['posture'] == 2) {
                            $posture = "微挺";
                        } elseif ($measure['posture'] == 3) {
                            $posture = "正常";
                        } elseif ($measure['posture'] == 4) {
                            $posture = "微驼";
                        } elseif ($measure['posture'] == 5) {
                            $posture = "驼背";
                        } else {
                            $posture = '正常';
                        }

                        $order_data[$mid] = array(
                            '1' => $v['id'],
                            '2' => '&nbsp',
                            '3' => $measure['measure_name'],
                            '4' => round($measure['height'], 1),
                            '5' => round($measure['weight'], 1),
                            '6' => $measure['age'],
                            '7' => $shoulder,
                            '8' => $chest_type,
                            '9' => $stomach_type,
                            '10' => $posture,
                            '11' => '&nbsp',
                            '12' => round($measure['neck'], 1),
                            '13' => round($measure['shirt'], 1),
                            '14' => round($measure['chest'], 1),
                            '15' => round($measure['stomach'], 1),
                            '16' => round($measure['pants_hips'], 1),
                            '17' => round($measure['jacket_back'], 1),
                            '18' => round($measure['sleeve'], 1),
                            '19' => round($measure['bicep'], 1),
                            '20' => round($measure['wrist'], 1),
                            '21' => '&nbsp',
                            '22' => round($measure['pants'], 1),
                            '23' => round($measure['waist'], 1),
                            '24' => round($measure['pants_hips'], 1),
                            '25' => round($measure['thigh'], 1),
                            '26' => round($measure['knee'], 1),
                            '27' => '&nbsp',
                            '28' => round($measure['crotch'], 1),
                            '29' => $v['delivery_email'],
                            '30' => $v['delivery_first_name'] . ' ' . $v['delivery_last_name'],
                            '31' => $suppliers_name,
                        );
                    }
                }
                foreach ($order_data as $data) {
                    $pack_arr[] = $data;
                }
            }
            import('COM.XmlExcel');
            $excel = new XmlExcel;
            $excel_title = array('订单ID', '&nbsp', '名字', '身高', '体重', '年龄'
            , '肩', '胸', '肚', '背', '号型', '领围', '衣长', '胸围', '腰围', '下摆', '肩宽', '袖长'
            , '袖肥', '袖口', '号型', '裤长', '腰围', '臀围', '横档', '中档', '脚口', '直档', 'Email地址', '收货姓名', '面料编号');
            $excel->setSheetHead($excel_title);
            $excel->addRows($pack_arr);
            $excel->setDefaultWidth(100);
            $excel->export('客户尺寸统计表' . date('Ymd_His'));
        }
    }

    //批量打印工厂制作单
    function print_pro_note()
    {
        $ids = $_GET['ids'];
        $ids = explode(',', $ids);
        if (!$ids) {
            echo '参数错误';
            exit;
        }
        $order_item = array();
        foreach ($ids as $key => $order_id) {
            if (intval($order_id) > 0 && OrderModel::isset_size($order_id)) {
                //查询订单子数据
                $product = OrderModel::getOrderProductList($order_id); //订单产品列表
                foreach ($product as $k => $v) {
                    if ($v['custom_type']) {
                        $order_item[]['id'] = $v['id'];
                    }
                }
            }
        }

        $this->assign('order_item', $order_item);
        $this->display('print_pro_note');
    }

    //扫描订单 ，打印in文件
    function order_scan()
    {
        if ($_POST['dosubmit']) {
            $orderstr = preg_split('/\n/', $_POST['orders']);
            $neatOders = array();
            $neatItems = array();
            foreach ($orderstr as $key => $val) {
                if (!trim($val)) continue; //值非空
                if(strstr($val,'M')){
                    $decollator = 'M';
                }else{
                    $decollator = '-';
                }
                $val_arr = explode($decollator, $val);
                $order = $val_arr[0];
                $item = $val_arr[1];
                //同时排除重复项
                if (!in_array($order, $neatOders)) {
                    $neatOders[] = $order;
                }
                if (isset($neatItems[$order])) {
                    if (!in_array($item, $neatItems[$order])) {
                        $neatItems[$order][] = $item;
                    }
                } else {
                    $neatItems[$order][] = $item;
                }
            }
            //重量
            //三件套2kg  两件套2kg  单上衣1.5kg  单裤0.5kg  单马夹0.5kg  大衣2kg  风衣1.5kg  衬衫0.5kg   多件时系统自动计算（配件重量可忽略）
            //hs 描述
            $accData = array(
                '2061' => array(
                    'hs' => '6103101000',
                    'ms' => "Man's 100% Wool Coat",
                    'usprice' => '49',
                    'price' => '19',
                    'weight' => '12',
                ),
                '2093' => array(
                    'hs' => '6103101000',
                    'ms' => "Man's 100% Wool Coat",
                    'usprice' => '49',
                    'price' => '19',
                    'weight' => '10',
                ),
                '2066' => array(
                    'hs' => '6103101000',
                    'ms' => "Man's 100% Wool Coat",
                    'usprice' => '49',
                    'price' => '19',
                    'weight' => '20',
                ),
                '2104' => array(
                    'hs' => '6103101000',
                    'ms' => "Man's 100% Wool Coat",
                    'usprice' => '49',
                    'price' => '19',
                    'weight' => '6',
                ),
                '2103' => array(
                    'hs' => '6103101000',
                    'ms' => "Man's 100% Wool Pants",
                    'usprice' => '15',
                    'price' => '9',
                    'weight' => '4',
                ),
                '2102' => array(
                    'hs' => '6103101000',
                    'ms' => "Man's 100% Wool Vest",
                    'usprice' => '15',
                    'price' => '9',
                    'weight' => '2',
                ),
                '2062' => array(
                    'hs' => '6105100091',
                    'ms' => "Man's 100% Cotton Shirt",
                    'usprice' => '15',
                    'price' => '9',
                    'weight' => '2',
                ),
                '2067' => array(//配件
                    'hs' => '',
                    'ms' => "Men's business accessories",
                    'usprice' => '5',
                    'price' => '3',
                    'weight' => '1',
                ),
                '2106' => array(//面料卡
                    'hs' => '',
                    'ms' => "Men's business accessories",
                    'usprice' => '5',
                    'price' => '3',
                    'weight' => '1',
                ),
                '2163' => array(//男士皮鞋
                    'hs' => '6403190090',
                    'ms' => "Man's Leather Shoes",
                    'usprice' => '49',
                    'price' => '19',
                    'weight' => '20',
                ),
            );

            $inData = array();
            foreach ($neatOders as $val) {
                $order_id = $val;
                if (!$neatItems[$order_id]) continue;
                $orderInfo = OrderModel::getOrderInfo($order_id);
                if (!$orderInfo) continue;

                $Packaging_type = '03';
                $Service_Type = 3;
                $hs = array(); //hs
                $ms = array();; //描述
                $price = array();
                $weight = 10;
                $qty = array();
                $catidArr = array();
                $fabric = false; //2、只有面料卡；4、面料卡+配件； 2015-06-12 改变
                //查询订单下商品信息
                foreach ($neatItems[$order_id] as $order_item_id) {
                    $order_items_db = D('orders_items');
                    $order_item_info = $order_items_db->find($order_item_id);
                    $product_db = D('product');
                    $catid = $product_db->where(array('id' => $order_item_info['product_id']))->getField('catid');
                    $parentid = CategoryModel::get_category_parentid($catid);
                    $catid = $parentid > 0 ? $parentid : $catid;
                    //只要有两件套、三件套 单西或大衣的一种，就用“自备包装”，其他情况都用“FEDEX快递袋”
                    if (in_array($catid, array(2061, 2093, 2066, 2104))) {
                        $Packaging_type = '01';
                    }
                    //订单商品如下情况，用“国际优先快递服务”：1、只有衬衫；2、只有面料卡；
                    //3、衬衫+配件；4、面料卡+配件；5、衬衫+面料卡，其他情况都用“国际经济快递服务”
                    // if (in_array($catid, array(2061, 2093, 2066, 2104, 2103, 2102))) {
                    //     $Service_Type = 3;
                    // }
                    $catidArr[$catid] = true;
                    

                    //国家
                    $country = M('region')->where(array('name' => $orderInfo['delivery_country']))->getField('iso2_code');
                    //美国加拿大计算独立价格
                    $price_field = 'price';
                    if (in_array($country, array('US', 'CA'))) {
                        $price_field = 'usprice';
                    }
                    foreach ($accData as $k_catid => $v_data) {
                        if ($k_catid == $catid) {
                            $hs[] = $v_data['hs'];
                            $ms[] = $v_data['ms'];
                            $price[] = $v_data[$price_field];
                            $weight += $v_data['weight']*$order_item_info['qty'];
                            $qty[] = $order_item_info['qty'];
                        }
                    }
                }

                // $hs = trim($hs, ',');
                // $ms = trim($ms, ',');
                //if ($weight < 5) $weight = 5;
                
                //订单商品如下情况，用“国际优先快递服务”：
                //2、只有面料卡；4、面料卡+配件； 2015-06-12 改变
                if(isset($catidArr[2106])){
                    if(count($catidArr) == 1){
                        $Service_Type = 1;
                    }else if(count($catidArr) == 2 && isset($catidArr[2067])){
                        $Service_Type = 1;
                    }   
                }

                $inData[] = '0,"20"';
                $inData[] = '1,"' . $order_id . '"';
                $inData[] = '4,"OWNONLY CORPORATION"';
                $inData[] = '5,"2F 205 #22 CHANGCHENG ST"';
                $inData[] = '6,"SHIQIAO RD XIACHENG DSITRICT"';
                $inData[] = '7,"HANGZHOU"';
                $inData[] = '9,"310021"';
                $inData[] = '10,"516523727"';
                $inData[] = '11,""';
                $inData[] = '12,"' . $orderInfo['delivery_first_name'] . ' ' .
                    $orderInfo['delivery_last_name'] . '"';
                $inData[] = '13,"' . $orderInfo['delivery_address'] . '"';
                if ($orderInfo['delivery_address2']) {
                    $inData[] = '14,"' . $orderInfo['delivery_address2'] . '"';
                }
                $inData[] = '15,"' . $orderInfo['delivery_city'] . '"';
                $inData[] = '16,"' . $orderInfo['delivery_province'] . '"';
                $inData[] = '17,"' . $orderInfo['delivery_postcode'] . '"';
                $inData[] = '18,"' . $orderInfo['delivery_phone'] . '"';
                $inData[] = '20,"516523727"';
                $inData[] = '21,"' . $weight . '"';
                $inData[] = '23,"1"';
                $inData[] = '25,"' . $order_id . '"';
                $inData[] = '32,"OWNONLY"';
                $inData[] = '50,"' . $country . '"';
                $inData[] = '57-1,"9"';
                $inData[] = '58-1,"55"';
                $inData[] = '59-1,"55"';
                $inData[] = '68,"USD"';
                $inData[] = '70,"2"';
                $inData[] = '71,""';
                $inData[] = '72,"6"';
                $inData[] = '75,"KGS"';
                foreach ($hs as $hskey => $hsval) {
                    $keyStr = (count($hs) == 1) ? '' : '-'.($hskey+1);
                    $inData[] = '79'.$keyStr.',"' . $ms[$hskey] . '"';
                    $inData[] = '80'.$keyStr.',"CN"';
                    $inData[] = '81'.$keyStr.',"' . $hsval . '"';
                    $inData[] = '82'.$keyStr.',"' . $qty[$hskey] . '"';
                    $inData[] = '414'.$keyStr.',"PCS"';
                    $inData[] = '1030'.$keyStr.',"' . ($price[$hskey] * 1000000) . '"';
                }  
                $inData[] = '113,"Y"';
                $inData[] = '116,"1"';
                $inData[] = '117,"CN"';
                $inData[] = '183,"8657187313525"';
                $inData[] = '1150,"OWNONLY"';
                $inData[] = '1273,"' . $Packaging_type . '"';
                $inData[] = '1274,"' . $Service_Type . '"';
                $inData[] = '2397,"4"';
            }
            //echo "<pre />";print_r($inData);exit;
            $str = "";
            foreach ($inData as $key => $val) {
                $str .= $val . "\r\n";
            }
            $filename = "trans_" . date('YmdHis') . ".in";
            header("Content-type: text/plain");
            header("Accept-Ranges: bytes");
            header("Content-Disposition: attachment; filename=" . $filename);
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Pragma: no-cache");
            header("Expires: 0");
            exit($str);
        }
        $this->display('order_scan');
    }
    
    //报文配置数据
    function settlementConfig(){
        $config = array(
            2093 => array('pinming' => '男士西服', 'pinmingEn' => 'Man\'s 100% Wool Coat', 'haiguancode' => '6103101000', 'weight' => '1'),
            2061 => array('pinming' => '男士西服', 'pinmingEn' => 'Man\'s 100% Wool Coat', 'haiguancode' => '6103101000', 'weight' => '1.2'),
            2066 => array('pinming' => '男士大衣', 'pinmingEn' => 'Man\'s 101% Wool Coat', 'haiguancode' => '6103101000', 'weight' => '2'),
            2104 => array('pinming' => '男士单西', 'pinmingEn' => 'Man\'s 103% Wool Coat', 'haiguancode' => '6103101000', 'weight' => '0.6'),
            2103 => array('pinming' => '男士西裤', 'pinmingEn' => 'Man\'s 100% Wool Pants', 'haiguancode' => '6103101000', 'weight' => '0.4'),
            2102 => array('pinming' => '男士马甲', 'pinmingEn' => 'Man\'s 100% Wool Vest', 'haiguancode' => '6103101000', 'weight' => '0.2'),
            2062 => array('pinming' => '男士衬衫', 'pinmingEn' => 'Man\'s 100% Cotton Shirt', 'haiguancode' => '6105100091', 'weight' => '0.2'),
            2163 => array('pinming' => '男士皮鞋', 'pinmingEn' => 'Man\'s Leather Shoes', 'haiguancode' => '6403190090', 'weight' => '2'),
            2076 => array('pinming' => '男士领带', 'pinmingEn' => 'Man\'s 100% Silk Tie ', 'haiguancode' => '6215100090', 'weight' => '0.1'),
            2098 => array('pinming' => '男士方巾', 'pinmingEn' => 'Man\'s 100% Silk Pocket Square', 'haiguancode' => '6214300000', 'weight' => '0.1'),
            2077 => array('pinming' => '男士领结', 'pinmingEn' => 'Man\'s 100% Silk Bow Tie', 'haiguancode' => '6215100011', 'weight' => '0.1'),
            2130 => array('pinming' => '男士皮带', 'pinmingEn' => 'Man\'s 100% Leather Belt', 'haiguancode' => '4203301090', 'weight' => '0.1'),
            2079 => array('pinming' => '男士袖扣', 'pinmingEn' => 'Man\'s Copper Cufflink', 'haiguancode' => '7113119090', 'weight' => '0.1'),
            2080 => array('pinming' => '男士领夹', 'pinmingEn' => 'Man\'s Copper Tie Clip', 'haiguancode' => '7113119090', 'weight' => '0.1'),
            2081 => array('pinming' => '男士胸针', 'pinmingEn' => 'Man\'s Copper Brooch', 'haiguancode' => '7113119090', 'weight' => '0.1'),
            2078 => array('pinming' => '男士围巾', 'pinmingEn' => 'Cashmere Scarf', 'haiguancode' => '6214202000', 'weight' => '0.1'),
        );

        $product_config = array(
            505 => array('pinming' => '面料色卡', 'pinmingEn' => 'Fabric Swatches', 'haiguancode' => '5111119000', 'weight' => '0.1'),
            326 => array('pinming' => '量体皮尺', 'pinmingEn' => 'Tape Measure', 'haiguancode' => '9017800000', 'weight' => '0.1'),
            327 => array('pinming' => '木质衣架', 'pinmingEn' => 'Superba Hugger', 'haiguancode' => '4421100090', 'weight' => '0.1'),
            328 => array('pinming' => '木质毛刷', 'pinmingEn' => 'Superba Brush', 'haiguancode' => '9603909090', 'weight' => '0.1'),
            398 => array('pinming' => '男士衬衫插片', 'pinmingEn' => 'Shirt Collar Stay (Shell)/Brushed Stainless Steel Inlay', 'haiguancode' => '5603949090', 'weight' => '0.1'),
            399 => array('pinming' => '男士衬衫插片', 'pinmingEn' => 'Shirt Collar Stay (Shell)/Brushed Stainless Steel Inlay', 'haiguancode' => '5603949090', 'weight' => '0.1'),
            397 => array('pinming' => '男士衬衫插片', 'pinmingEn' => 'Shirt Collar Stay (Shell)/Brushed Stainless Steel Inlay', 'haiguancode' => '5603949090', 'weight' => '0.1'),
            287 => array('pinming' => '男士衬衫插片', 'pinmingEn' => 'Shirt Collar Stay (Shell)/Brushed Stainless Steel Inlay', 'haiguancode' => '5603949090', 'weight' => '0.1'),
            357 => array('pinming' => '竹质U盘', 'pinmingEn' => 'U Disk', 'haiguancode' => '8471609000', 'weight' => '0.1'),
        );

        $data = array(
            'config' => $config,
            'product_config' => $product_config,
            ); 
        return $data;       
    }   

    //电子口岸退税清单
    function settlement(){
        $order_db     = M('orders');
        $order_item   = M('orders_items');
        $product_item = M('product_items');
        $product_db   = M('product');
        $delivery_db  = M('orders_delivery');
        $delivery_product_db = M('orders_delivery_product');
        
        //报文配置数据
        $settlementConfig = $this->settlementConfig();
        $config = $settlementConfig['config'];
        $product_config = $settlementConfig['product_config'];

        $did = $_REQUEST['did']; 
        $delivery = $delivery_db->where(array('id'=>$did))->find();
        if(!$delivery){
            echo "发货记录不存在!";exit;
        }
        $order_info = $order_db->field('id,payment_method,delivery_cid,order_sn,shipping_method,order_amount,pay_amount,delivery_country,payment_time,payment_status,shipping_time,delivery_email,delivery_first_name,delivery_last_name')->where(array('id'=>$delivery['order_id']))->find();       
        if(!$order_info){
            echo "订单记录不存在!";exit;
        }

        $region = D('region')->where(array('id'=>$order_info['delivery_cid']))->find();        
        $destinationCountry = $region['destinationCountry'];
        $consigneeCountry   = $region['iso3_code'];

        $totalPrice = 0;
        $packageNo  = 0;
        $netWeight  = 0;
        $item_product = array();   
        $delivery_product = $delivery_product_db->where(array('orders_delivery_id'=>$did))->select();
        foreach ($delivery_product as $key => $val) {
            $orders_item = M('orders_items')->field('orders_items.*,product.*,orders_items.id as orders_items_id')->join('left join product on orders_items.product_id=product.id')->where('orders_items.id=' . $val['orders_items_id'])->find();
            $pinming = '';
            $pinmingEn = '';
            $haiguancode = '';
            $weight = '';
            if ($product_config[$orders_item['product_id']]) {
                $pinming = $product_config[$orders_item['product_id']]['pinming'];
                $pinmingEn = $product_config[$orders_item['product_id']]['pinmingEn'];
                $haiguancode = $product_config[$orders_item['product_id']]['haiguancode'];
                $weight = $product_config[$orders_item['product_id']]['weight'];
            } else {
                //先用catid查询 ，如果没有用分类父id
                if ($config[$orders_item['catid']]) {
                    $findCatid = $orders_item['catid'];
                }else{
                    $findCatid = CategoryModel::get_category_parentid($orders_item['catid']);
                }
                $pinming = $config[$findCatid]['pinming'];
                $pinmingEn = $config[$findCatid]['pinmingEn'];
                $haiguancode = $config[$findCatid]['haiguancode'];
                $weight = $config[$findCatid]['weight'];
            }  
            //销售价格         
            if ($orders_item['attribute_type']==1) {
                $price_sale = $orders_item['custom_price'];
            } else {
                $price_sale = $orders_item['advanced_price'];                        
            }                      
            $item_product_one = array(
                    'goodsName' => $pinming,
                    'goodsNo'   => $haiguancode,
                    'weight'    => $weight,
                    'goodsAmount' => $val['send_number'],
                    'unitPrice'   => floatval($price_sale),
                    'totalPrice'  => floatval($price_sale * $orders_item['qty']),
                    'goodsUnit'   => '011',
                    'goodsUnit1'  => '006',
                    'goodsUnit2'  => '011',
                    'goodsAmount1' => $orders_item['qty'],
                    'goodsAmount2' => $orders_item['qty'],
                    'currency' => '502',
                    'dutyMode' => '1',
                    'goodsModel' => $orders_item['sn'],
                );
            $item_product[] = $item_product_one;
                      
            $totalPrice += ($price_sale * $orders_item['qty']);
            $packageNo += $orders_item['qty'];
            $netWeight += ($weight * $orders_item['qty']);
            
        }
        // echo "<pre />";var_dump($item_product); exit;
        //header("Content-type:text/xml");
        //拼接XML数据
        $xmlStr ='';
        $xmlStr .='<?xml version="1.0" encoding="UTF-8"?>'; 
        $xmlStr .='<mo version="1.0.0">';
        $xmlStr .='<head>';
        $xmlStr .='<businessType>BILL</businessType>';
        $xmlStr .='</head>';
        $xmlStr .='<body>';
        $xmlStr .='<jkfGoodsList>';
            $xmlStr .='<jkfGoods>'; 
                $xmlStr .='<jkfSign>';
                    $xmlStr .='<companyCode>094776984</companyCode>';
                    $xmlStr .='<businessNo>'.$delivery['delivery_sn'].'</businessNo>';
                    $xmlStr .='<businessType>BILL</businessType>';
                    $xmlStr .='<declareType>1</declareType>';
                    $xmlStr .='<note></note>';
                $xmlStr .='</jkfSign>';
                $xmlStr .='<jkfOrderInfo>';
                    $xmlStr .='<orderNo>'.$order_info['order_sn'].'</orderNo>';
                    $xmlStr .='<payName>'.$order_info['payment_method'].'</payName>';
                    $xmlStr .='<currency>502</currency>';
                    $xmlStr .='<payTime>'.$order_info['payment_time'].'</payTime>';
                    $xmlStr .='<shippingTime>'.$delivery['update_time'].'</shippingTime>';
                    $xmlStr .='<goodsNum>'.$packageNo.'</goodsNum>';
                    $xmlStr .='<rate>6.2</rate>';
                    $xmlStr .='<orderTotalAmount>'.$totalPrice.'</orderTotalAmount>';
                    $xmlStr .='<realShippingId>2</realShippingId>';
                    $xmlStr .='<agentCode>094776984</agentCode>';
                    $xmlStr .='<agentName>杭州乐尚进出口有限公司</agentName>';
                    $xmlStr .='<ownerCode>094776984</ownerCode>';
                    $xmlStr .='<ownerName>杭州乐尚进出口有限公司</ownerName>';
                    $xmlStr .='<customsCode>2928</customsCode>';
                    $xmlStr .='<declareCode>330198Z006</declareCode>';
                    $xmlStr .='<declareName>联邦快递（中国）有限公司杭州分公司</declareName>';
                    $xmlStr .='<consignee>'.$order_info['delivery_first_name'].' '.$order_info['delivery_last_name'].'</consignee>';
                    $xmlStr .='<consigneeCountry>'.$destinationCountry.'</consigneeCountry>';                                           
                $xmlStr .='</jkfOrderInfo>';
                $xmlStr .='<jkfMerchBills>';
                    $xmlStr .='<jkfMerchBill>';
                        $xmlStr .='<wayBillNo>'.$delivery['shipping_no'].'</wayBillNo>';
                        $xmlStr .='<orderNo>'.$order_info['order_sn'].'</orderNo>';
                        $xmlStr .='<destinationCountry>'.$destinationCountry.'</destinationCountry>';
                        $xmlStr .='<taxMode>1</taxMode>'; 
                        $xmlStr .='<wrapType>2</wrapType>'; 
                        $xmlStr .='<companyCode>094776984</companyCode>'; 
                        $xmlStr .='<companyName>杭州乐尚进出口有限公司</companyName>';
                        $xmlStr .='<customsCode>2928</customsCode>';
                        $xmlStr .='<IEPort>2928</IEPort>'; //2928
                        $xmlStr .='<ieFlag>E</ieFlag>';
                        $xmlStr .='<totalPrice>'.$totalPrice.'</totalPrice>';
                        $xmlStr .='<packageNo>'.$packageNo.'</packageNo>';
                        $xmlStr .='<grossWeight>'.($netWeight+1).'</grossWeight>';  //包装加1kg
                        $xmlStr .='<postMode>2</postMode>';
                        $xmlStr .='<exchangeRate>6.2</exchangeRate>';
                        $xmlStr .='<netWeight>'.$netWeight.'</netWeight>';
                        $xmlStr .='<logisCompanyCode>330198Z006</logisCompanyCode>';
                        $xmlStr .='<logisCompanyName>联邦快递（中国）有限公司杭州分公司</logisCompanyName>';
                        $xmlStr .='<transMode>5</transMode>';
                        $xmlStr .='<tradeMode>9610</tradeMode>';
                        $xmlStr .='<jkfMerchBillDetails>';    
                        foreach ($item_product as $item_product_one) { 
                            $xmlStr .='<jkfMerchBillDetail>';
                            foreach ($item_product_one as $key=>$val) {
                                $xmlStr .='<'.$key.'>'.$val.'</'.$key.'>';
                            }
                            $xmlStr .='</jkfMerchBillDetail>';  
                        }    
                        $xmlStr .='</jkfMerchBillDetails>';             
                    $xmlStr .='</jkfMerchBill>';
                $xmlStr .='</jkfMerchBills>';
            $xmlStr .='</jkfGoods>';
        $xmlStr .='</jkfGoodsList>';
        $xmlStr .='</body>';
        $xmlStr .='</mo>';
        //echo $xmlStr; exit;
        $path = dirname(__FILE__) . '/tuishui';
        if (!is_dir($path)) { mkdir($path); }
        $file_name_path = $path . '/' . $delivery['delivery_sn'] . '.txt';
        file_put_contents($file_name_path, $xmlStr);

        //发送数据
        ini_set("soap.wsdl_cache_enabled", 0);
        $params = array('xmlStr'=>$xmlStr,'xmlType'=>'BILL','sourceType'=>'1');
        if($_SERVER['HTTP_HOST'] == "www.ownonly.com" || $_SERVER['HTTP_HOST'] == "ownonly.com" )
        {   //正式地址
            $wsdl = "http://122.224.69.179:8080/newyorkWS/ws/ReceivedDeclare?wsdl";
        }else{
            $wsdl = "http://122.224.230.4:18003/newyorkWS/ws/ReceivedDeclare?wsdl";
        }
        try {
            $soap = new SoapClient($wsdl, array('trace' => true, 'cache_wsdl' => WSDL_CACHE_NONE, 'soap_version' => SOAP_1_1,'encoding'=>'UTF-8'));
            $method = "checkReceived";
            $result = $soap -> $method($params);
        } catch(Exception $e) {
            echo "Exception: " . $e -> getMessage(); exit;
        }
        //print_r($result->return);        
        //获取结果
        $xmlRes = $result->return;
        $xml = new SimpleXMLElement($xmlRes); 
        $jkfResult = get_object_vars($xml->body->list->jkfResult); 
        $chkMark = $jkfResult['chkMark'];
        if($chkMark == '1'){
            $delivery_db->where(array('id' => $did))->save(array('settlement' => 1,'settlement_send_time' => date('Y-m-d H:i:s') ));
            echo '1';
        }else{
            //得到错误原因
            $resultInfo = "发生错误!\n";
            foreach ($xml->body->list->jkfResult->resultList->jkfResultDetail as $jkfResultDetail) { 
                $jkfResultDetail = get_object_vars($jkfResultDetail); 
                $resultInfo .= $jkfResultDetail['resultInfo']."\n";
            }
            echo  $resultInfo; 
        }
    }

    //退税报文对应Fedex excel下载
    function settlementfedex(){
        
        if(!$_POST['sn']){
            $this->display('settlementfedex');exit;
        }

        $order_db     = M('orders');
        $order_item   = M('orders_items');
        $product_item = M('product_items');
        $product_db   = M('product');
        $delivery_db  = M('orders_delivery');
        $delivery_product_db = M('orders_delivery_product');

        //报文配置数据
        $settlementConfig = $this->settlementConfig();
        $config = $settlementConfig['config'];
        $product_config = $settlementConfig['product_config'];
        
        //获取流水号
        $sn = preg_split('/\n/', $_POST['sn']);
        $snArr = array();
        foreach ($sn as $key => $val) {
            if (!trim($val)) continue; //值非空
            $snArr[] = trim($val);
        }

        $ext_arr = array();
        
        foreach ($snArr as $delivery_sn) {
            $delivery = $delivery_db->where(array('delivery_sn'=>$delivery_sn))->find();
            $order_info = $order_db->field('id,payment_method,delivery_cid,order_sn,shipping_method,order_amount,pay_amount,delivery_country,payment_time,payment_status,shipping_time,delivery_email,delivery_first_name,delivery_last_name')->
                where(array('id'=>$delivery['order_id']))->find(); 
            $delivery_product = $delivery_product_db->where(array('orders_delivery_id'=>$delivery['id']))->select();
            $kgone = 0;
            foreach ($delivery_product as $val) {
                $orders_item = M('orders_items')->field('orders_items.*,product.*,orders_items.id as orders_items_id')
                    ->join('left join product on orders_items.product_id=product.id')
                    ->where('orders_items.id=' . $val['orders_items_id'])->find();    
                $pinming = '';
                $pinmingEn = '';
                $haiguancode = '';
                $weight = '';
                if ($product_config[$orders_item['product_id']]) {
                    $pinming = $product_config[$orders_item['product_id']]['pinming'];
                    $pinmingEn = $product_config[$orders_item['product_id']]['pinmingEn'];
                    $haiguancode = $product_config[$orders_item['product_id']]['haiguancode'];
                    $weight = $product_config[$orders_item['product_id']]['weight'];
                } else if ($config[$orders_item['catid']]) {
                    $pinming = $config[$orders_item['catid']]['pinming'];
                    $pinmingEn = $config[$orders_item['catid']]['pinmingEn'];
                    $haiguancode = $config[$orders_item['catid']]['haiguancode'];
                    $weight = $config[$orders_item['catid']]['weight'];
                }   
                $product = D('product')->where(array('id' => $orders_item['product_id']))->find();
                $totalWeight = $val['send_number'] * $weight;
                if($kgone == 0) $totalWeight += 1; //加1kg的包装

                $data = array(
                    $order_info['order_sn'],
                    $haiguancode,
                    $pinming,
                    '千克',
                    '',
                    $val['send_number'],
                    $totalWeight,              
                    (int)$product['advanced_price'] != 0 ? $product['advanced_price'] : $product['custom_price'],
                    'USD', 
                    ((int)$product['advanced_price'] != 0 ? $product['advanced_price'] : $product['custom_price']) * $val['send_number'],//
                    $order_info['delivery_country'],
                    'fedex',//$shipping[$v['shipping_id']],
                    $delivery['shipping_no'],
                    $delivery['update_time'] ? date('Ymd', $delivery['update_time']) : '',
                    'ownonly',
                );
                $ext_arr[] = $data;
                $data = array();
                $kgone++;
            }
        }

        import('COM.XmlExcel');
        $excel = new XmlExcel;
        $excel_title = array('订单号', '编号', '中文品名', '单位', '海关法定单位代码', '数量', '重量', '单价', '币种',  '金额', '国家', '物流', '运单号', '发货日期', '发件人');
        $excel->setSheetHead($excel_title);
        $excel->addRows($ext_arr);
        $excel->export('Fedex excel' . date('ymdHis'));     

    }

    //shoes导出word
    function shoesWord(){
        $order_item_id  = $_REQUEST['order_item_id'];
        $order_items_db = D('orders_items');
        $item_info = $order_items_db->find($order_item_id);
        $docName   = $item_info['order_id'].'-'.$item_info['id'];
        header("Content-Type:   application/msword");       
        header("Content-Disposition:   attachment;   filename=".$docName.".doc"); //指定文件名称  
        header("Pragma:   no-cache");
        header("Expires:   0");
        $html = file_get_contents('http://' . $_SERVER['HTTP_HOST'] . U('order/order_print_figure_god', 'order_item_id=' . $order_item_id));
        echo  $html;
        exit;       
    }
	
	public function getExcel(){
		$where['payment_status'] = array("in",array(1,2,3));
		$orders=D("orders")->field("count(id) as tl,user_id,delivery_first_name,delivery_last_name,delivery_email,sum(pay_amount) as pay_total")->where($where)->group("user_id")->select();
        $date = date('Y',time());
		$orders = $this->arraySort($orders, 'tl', 'desc');
		$results= array();
		$i=0;
        $num = array();
		if($orders && count($orders)>0){
			foreach($orders as $val){
			    if($val['tl']>30){
                    continue;
                }
				$condition['payment_status'] = array("in",array(1,2,3));
				$condition['user_id']	 	 = $val['user_id'];
				$user_orders=D("orders")->field("order_sn,pay_amount,start_time")->where($condition)->order("id desc")->select();
				$user_orders_arr = array();

                /*
				foreach($user_orders as $v){
				    if($date == date('Y',$v['start_time'])){
                        $user_orders_arr[$date][] = $v['order_sn']."(".$v['pay_amount'].")";
                    }else if(($date-1) == date('Y',$v['start_time'])){
                        $user_orders_arr[$date-1][] = $v['order_sn']."(".$v['pay_amount'].")";
                    }else if(($date-2) == date('Y',$v['start_time'])){
                        $user_orders_arr[$date-2][] = $v['order_sn']."(".$v['pay_amount'].")";
                    }else{
                        $user_orders_arr['other'][] = $v['order_sn']."(".$v['pay_amount'].")";
                    }
				}
                 */

                foreach($user_orders as $v){
                    array_push($user_orders_arr,$v['order_sn']."(".$v['pay_amount'].")");

                }
				$results[$i]['name'] 		= $val['delivery_first_name'].$val['delivery_last_name'];
				$results[$i]['order_count'] = $val['tl'];
				$results[$i]['email'] 		= $val['delivery_email'];
				$results[$i]['money'] 		= $val['pay_total'];

                /*
                if(!empty($user_orders_arr[$date])){
                    $results[$i]['order_sn_'.$date] 	= count($user_orders_arr[$date])==0?"":implode(",",$user_orders_arr[$date]);
                }
				if(!empty($user_orders_arr[$date-1])){
                    $results[$i]['order_sn_'.($date-1)] 	= count($user_orders_arr[$date-1])==0?"":implode(",",$user_orders_arr[$date-1]);
                }
                if(!empty($user_orders_arr[$date-2])){
                    $results[$i]['order_sn_'.($date-2)] 	= count($user_orders_arr[$date-2])==0?"":implode(",",$user_orders_arr[$date-2]);
                }
                if(!empty($user_orders_arr['other'])){
                    $results[$i]['order_sn_other'] 	= count($user_orders_arr['other'])==0?"":implode(",",$user_orders_arr['other']);
                }
                */

                if($user_orders_arr){
                    foreach($user_orders_arr as $key=>$val){
                        $results[$i]['order_sn_'.$key] 	= $val;
                        $num[$key] = $key;
                    }
                }
				$i++;
			}
		}
		$xlsName  = "下单量排行";
        /*
		$xlsCell  = array(
			array('name','会员名称'),
			array('order_count','总购买次数'),
			array('email','邮箱'),
			array('money','总支付金额'),
			array('order_sn_'.($date),$date.'年订单号'),
            array('order_sn_'.($date-1),($date-1).'年订单号'),
            array('order_sn_'.($date-2),($date-2).'年订单号'),
            array('order_sn_other','其他年份订单号')
		);
        */
        $xlsCell  = array(
            array('name','会员名称'),
            array('order_count','总购买次数'),
            array('email','邮箱'),
            array('money','总支付金额')
        );
        foreach($num as $key=>$var){
            $xlsCell[] = array('order_sn_'.$key,'第'.($key+1).'单');
        }
		$this->exportExcel($xlsName,$xlsCell,$results);
	}
	
	private function arraySort($arr, $keys, $type = 'asc') {
        $keysvalue = $new_array = array();
        foreach ($arr as $k => $v){
            $keysvalue[$k] = $v[$keys];
        }
        $type == 'asc' ? asort($keysvalue) : arsort($keysvalue);
        reset($keysvalue);
        foreach ($keysvalue as $k => $v) {
           $new_array[$k] = $arr[$k];
        }
        return $new_array;
    }

    public function exportExcel($expTitle,$expCellName,$expTableData){
        $xlsTitle =  $expTitle;//文件名称
        $fileName = $expTitle.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        vendor("PHPExcel.PHPExcel");
        $objPHPExcel = new PHPExcel();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');

        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
        // $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
            }
        }

        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }


    //修改工艺类型
	public function edit_process_type(){
		$order_item_id	= I("get.order_item_id","","intval");
		$order_item = D("orders_items")->where(array("id"=>$order_item_id))->find();
		if(isset($_POST['dosubmit'])){
			$process_type = I("post.process_type","","trim");
			$id = I("post.id","","intval");
			if(D("orders_items")->where(array("id"=>$id))->save(array("process_type"=>$process_type))){
				 $this->success('操作成功', url('order/edit_process_type').'&order_item_id='.$id);exit;
			}
		}
		$this->assign("order_item",$order_item);
		$this->display();
	}
	//修改管理员修改订单备注
    public function edit_order_notes_by_admin(){
        $order_id	= I("get.order_id","","intval");
        $orders = D("orders")->where(array("id"=>$order_id))->find();
        if($orders){
            $admin_notes = I("post.admin_notes","","trim");
            if(D("orders")->where(array("id"=>$order_id))->save(array("admin_notes"=>$admin_notes))){
                $result['status']=1;
                $result['msg']="修改成功！";
            }else{
                $result['status']=0;
                $result['msg']="修改失败！";
            }
        }else{
            $result['status']=0;
            $result['msg']="未找到订单！";
        }
        echo json_encode($result);
        exit;
    }
	
    //导出订单的定制选项
    public function exportAttrExcel(){
       header('Content-Type: application/vnd.ms-excel;charset=gbk');
       header('Content-Disposition: attachment;filename="订单定制选项统计-'.date('Y-m-d H:i').'.csv"');
       header('Cache-Control: max-age=0');

        // 从数据库中获取数据
        $excel_start_time = isset($_GET['excel_start_time']) && $_GET['excel_start_time'] ? strtotime($_GET['excel_start_time']) : "";
        $excel_end_time = isset($_GET['excel_end_time']) && $_GET['excel_end_time'] ? strtotime($_GET['excel_end_time']) : "";
        $model_id = isset($_GET['model_id']) && $_GET['model_id'] ? $_GET['model_id'] : "";
        $where['orders.payment_status'] = array("in",array(1,2,3,4));
        $where['orders.start_time'][] = array("egt",$excel_start_time);
        $where['orders.start_time'][] = array("elt",$excel_end_time);
        if($model_id){
            $where['product.model_id'][] = array("eq",$model_id);
        }
        //$where['orders.id'] = 5474;
        $orderlist=D("orders_items")
            ->field("orders.user_id,orders.delivery_first_name,orders.delivery_last_name,orders.order_sn,orders.start_time,orders.order_amount,orders_items.attr,orders_items.custom_type")
            ->join('product ON orders_items.product_id=product.id')
            ->join('orders ON orders_items.order_id=orders.id')
            ->where($where)->select();
        $orderlist = $this->arraySort($orderlist, 'start_time', 'desc');

        // PHP文件句柄，php://output 表示直接输出到浏览器
        $fp = fopen('php://output', 'a');
        // 输出Excel列头信息
        $head = array('订单号','客户姓名','下单时间','金额', '定制选项');
        foreach ($head as $i => $v) {
            // CSV的Excel支持GBK编码，一定要转换，否则乱码
            $head[$i] = iconv('utf-8', 'gbk', $v);
        }
        // 写入列头
         fputcsv($fp, $head);

        // 计数器
        $cnt = 0;

        // 每隔$limit行，刷新一下输出buffer，节约资源
        $limit = 100000;

        // 逐行取出数据，节约内存
        foreach ($orderlist as $product) {
            $cnt ++;
            if ($limit == $cnt) { //刷新一下输出buffer，防止由于数据过多造成问题
                ob_flush();
                flush();
                $cnt = 0;
            }
            $addRowData = array();
            $addRowData[] = strtoupper($product['order_sn']);
            $addRowData[] = $product['delivery_first_name'].$product['delivery_last_name'];
            $addRowData[] = date('Y-m-d H:i:s',$product['start_time']);
            $addRowData[] = $product['order_amount'];
            $data = !empty($product['attr'])?unserialize($product['attr']):'';
            $attributes = array();
            foreach ($data as $vk => $val) {
                //获取定制选项中文名
                $where_attr = array('attribute_id' => $val["attr_id"],
                    'language_id' => 6);
                $cn_attr_name = D('attribute_items')->where($where_attr)->getField('name');
                if ($val["attr_value_id"]) {
                    //获取定制选项值在中文名
                    $where_attr_val = array('att_value_id' => $val["attr_value_id"],
                        'language_id' => 6);
                    $cn_attr_value_name = D('attribute_values_items')->where($where_attr_val)->getField('attr_value');
                } else {
                    $cn_attr_value_name = $val['attr_value'];
                }
                //解决more option里 订单商品定制数据显示不全的问题
                if(!isset($attributes[$val["attr_id"]])){
                    $attributes[$val["attr_id"]] = $cn_attr_name . ':' . $cn_attr_value_name;
                }else{
                    $attributes[$val["attr_id"]] .= ','.$cn_attr_value_name;
                }
            }
            $attribute = implode(' |  ', $attributes);

            $suppliers = M('suppliers')->where(array('suppliers_id'=>$product['suppliers_id']))->find();
            if($suppliers){
                $attribute['attr'] .= ' ,面料编号: '.$suppliers['suppliers_name'];
            }
            $addRowData[] = $attribute;
            $row = array();
            foreach ($addRowData as $i => $v) {
                $row[$i] = iconv('utf-8', 'gbk', $v);
            }
            fputcsv($fp, $row);
        }
    }
}